C++ Internals?


Here we will see the Class internals. Before that we will see Default constructors, which are related to internals. The default constructor is one constructor (defined by user or compiler) that does not take any argument. Now the question comes, why the default constructor is used?

If the default constructor is not given, the compiler will implicitly declare default constructor. Default constructors are used to initialize some class internals. It will not affect the data member of the class. The compiler inserts default constructor in some different situations. Suppose a class is derived from another class with default constructor, or one class ins containing object of some other class with default constructor. The compiler inserts code to call default constructor for the base class or the object which is placed inside current object.

Let us see one code to get the idea.

Example

#include<iostream>
using namespace std;
class Base {
   public:
      // compiler will create one constructor for the class "Base"
};
class ClassA {
   public:
   ClassA(){
      cout << "ClassA Constructor defined by user" << endl;
   }
   int x; //it will not be initialized
};
class ClassB : public ClassA {
   //compiler will create ClassB constructor and add some code to call
   ClassA constructor
};
class ClassC : public ClassA {
   public:
      ClassC() { //user defined consturctor, but compiler will add
         code to call A constructor
         cout << "User defined ClassC Constructor" << endl;
   }
};
class ClassD {
   public:
      ClassD(){
         // User defined default constructor. The compiler will add
         code to call object of ClassA
         cout << "User-defined consturctor for ClassD Constructor" <<
         endl;
   }
   private:
      ClassA obj;
};
int main() {
   Base baseObj;
   ClassB b;
   ClassC c;
   ClassD d;
}

Output

ClassA Constructor defined by user
ClassA Constructor defined by user
User defined ClassC Constructor
ClassA Constructor defined by user
User-defined consturctor for ClassD Constructor

Updated on: 31-Jul-2019

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements