(This question has been asked in GU Uni Dec 2018 for 7 Mark)

A constructor is a member function of a class, whose name is the same as the class name. A constructor is automatically called when an object of a class is created.

class MyClass {     // The class
  public:           // Access specifier
    MyClass() {     // Constructor
      cout << "Hello World!";
    }
};

int main() {
  MyClass myObj;    // Create an object of MyClass (this will call the constructor)
  return 0;
}

Below are the main characteristics of constructor

  • The name of the constructor must be the same as its class name.
  •  No return type can be specified for the constructor
  • A constructor can have a parameter list
  •  The constructor function can be overloaded
  •  They cannot be inherited but a derived class can call the base class constructor
  •  The compiler generates a constructor, in the absence of a user-defined constructor.
  •  Compiler generated constructor is a public member function
  • The constructor is executed automatically when the object is created
  •  A constructor can be used explicitly to create a new object of its class type
  • Constructor function cannot be declared “virtual”

Example,

#include <iostream>
using namespace std; 

class MyClass{
	public:
    int width;
    int height; 
	
    MyClass(int x, int y=0)
	{
	cout<<"Constructor with two arguments called"<<endl;
	 width=x;
	 height=y;
	}


	void getData()
	{
		cout<<"width:"<<width<<endl;
		cout<<"height:"<<height<<endl;
	}

};


int  main()
{
 
 
    MyClass obj1(5);
    MyClass obj2(3,6);


    obj1.getData();
    obj2.getData();
	return 0; 
}

OUTPUT

Constructor with two arguments called
Constructor with two arguments called
width:5
height:0
width:3
height:6

https://github.com/amitntrivedi/ObjectOrientedConceptsandProgramming/blob/master/Constructor%20and%20Destructor/CONOD.CPP

What is a constructor? Explain the characteristics of it in detail.

Leave a Reply

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