Default Methods in C++ with Examples

If we write a class that has no methods in it, and the class does not inherit from another class, the compiler will add six methods to it automatically. The methods which can be automatically generated by the compiler are:
 

  1. Default Constructor: It is equivalent to an empty default constructor. The default constructor is a constructor which can be called with no arguments. It is called when an instance is created without initialization.
     
class_name object_name;
  1. Consider a class derived from another class with the default constructor, or a class containing another class object with default constructor. The compiler needs to insert code to call the default constructors of base class/embedded object.
     

CPP




#include <iostream>
using namespace std;
  
class Base {
public:
    // compiler "declares" constructor
};
  
class A {
public:
    // User defined constructor
    A()
    {
        cout << "A Constructor" << endl;
    }
  
    // uninitialized
    int size;
};
  
class B : public A {
    // compiler defines default constructor of B, and
    // inserts stub to call A constructor
  
    // compiler won't initialize any data of A
};
  
class C : public A {
public:
    C()
    {
        // User defined default constructor of C
        // Compiler inserts stub to call A's constructor
        cout << "C Constructor" << endl;
  
        // compiler won't initialize any data of A
    }
};
  
class D {
public:
    D()
    {
        // User defined default constructor of D
        // a - constructor to be called, compiler inserts
        // stub to call A constructor
        cout << "D Constructor" << endl;
  
        // compiler won't initialize any data of 'a'
    }
  
private:
    A a;
};
  
int main()
{
    Base base;
  
    B b;
    C c;
    D d;
  
    return 0;
}



Output:

A Constructor
A Constructor
C Constructor
A Constructor
D Constructor

 

Contact Us