Class and Constructor
What is Class?
A class is like a blueprint for an object. It is a user defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class.
What is Constructor?
A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object(instance of class) create. It is special member function of the class.
How constructors are different from a normal member function?
A constructor is different from normal functions in following ways:
- Constructor has same name as the class itself
- Constructors don’t have return type
- A constructor is automatically called when an object is created.
- If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body).
Note: Class and Constructor name must be same.
//simple code #include<iostream> using namespace std; class Rectangle { private : int length,breadth; public : Rectangle(){ //constructor length=breadth=1; } Rectangle(int l,int b) //function overloading int area(); //accessor int perimeter(); //accesor int getLength(){ //accessor return length; } void setLength(int l){ //mutator length=l; ~Rectangle(); //destructor } Rectangle :: area() { return length * breadth; } int Rectangle :: perimeter() { return 2* (length + breadth); } Rectangle :: Rectangle(int l,int b) { length =l; breadth=b; } Rectangle :: ~Rectangle() {} } int main() { Rectangle r(10,5); cout<<r.area(); cout<<r.perimeter(); r.setLength(20); cout<<r.getLength(); }
Once’s the main function end destructor will automatically call because object is going outside scope.