C++ Program concept of Constructor

      No Comments on C++ Program concept of Constructor

It is a rule that the class and the constructor function within it must have same names.This is how the compiler knows that the member function is a Constructor.Constructor is a member function that is executed automatically whenever an object is created so no return type is used for constructor Since the constructor is called automatically when an object is created, returning value would not make any sense.

#include<iostream.h>
#include<conio.h>
class cons
{
 public:
  int x;
  cons(int y)
 {
   x=y;
 }
void display()
 {
  cout<<"value of x = "<<x;
 }
};

void main()
{
clrscr();
cons c1(10);
c1.display();
getch();
}

OUTPUT:-

Leave a Reply

Your email address will not be published. Required fields are marked *