Simple Example Program For Constructor In C++
On this page (7sections)
About this program
This is an example program in c constructor example programs. Read the concept first: Constructors and Destructors in C++ Classes, then study the code and output below.
Definition
In C++, Constructor is automatically called when an object ( a instance of the class) create.It is a special member function of the class.
- It has the same name of the class.
- It must be a public member.
- No Return Values.
- Default constructors are called when constructors are not defined for the classes.
for better understanding about Constructor,
Syntax
class class-name {
Access Specifier :
Member - Variables
Member - Functions
public:
class-name() {
// Constructor code
}
//... other Variables & Functions
}
Constructor Example Program
/* Example Program For Simple Example Program Of Constructor In C++
little drops @ thiyagaraaj.com
Coded By:THIYAGARAAJ MP */
#include<iostream>
#include<conio.h>
using namespace std;
class Example {
// Variable Declaration
int a, b;
public:
//Constructor
Example() {
// Assign Values In Constructor
a = 10;
b = 20;
cout << "Im Constructor\n";
}
void Display() {
cout << "Values :" << a << "\t" << b;
}
};
int main() {
Example Object;
// Constructor invoked.
Object.Display();
// Wait For Output Screen
getch();
return 0;
}
Sample Output
Im Constructor
Values :10 20
Related Pages
Learn the concept first, then study the code:
- C++ Programs — Browse all C++ Programs.
- Constructors and Destructors in C++ Classes — Tutorial — constructors, destructors and overloading.
- Simple Parameterized Constructor For Find Prime Number Example Program In C++ — More in c constructor example programs.
- Simple Example Program For Constructor Overloading In C++ — More in c constructor example programs.