Default Member-Functions Created by the Compiler Inside the C++
abhinav Ashok kumar
Curating Insights & Innovating in GPU Compiler | Performance Analyst at Qualcomm | LLVM Contributor | Maintain News Letter | AI/ML in Compiler
When we declare a class in C++
class Declare {};
The compiler then synthesis class as
class Declare {
public:
Declare(); // default constructor
Declare(const Declare&); // copy c'tor
Declare& operator=(Declare Thing&); // copy-assign
~Declare(); // d'tor
// C++11:
Declare(Declare&&); // move c'tor
Declare& operator=(Declare&&); // move-assign
};
But this is true till C++14
Way Class/Object Oriented Code Transform Into Sequential Code.
class Compiler_treat
{
int m_var;
public:
void print()
{
cout << m_var << endl;
}
};
The compiler will treat it as
class Compiler_treat
{
int m_var;
};
inline void print()
? {
? ? std::cout.operator<<(this->m_var).operator<<(std::endl);
? }
??
};
As you can see above object and methods are separate entity. An object only represent data members.
Therefore all the method in class/struct contain implicit this pointer as the first argument using which all non-static data member can be accessed.
Static data member are not part of class/struct. Because it usually resides in a data segment of memory layout. So it access directly or using segment register.
So this is the reason if you print the size of the above class , it print 4 because all method are a separate entity which operates on object by using implicit this pointer.
By the way
There are many factors that decide the size of an object of a class in C++.
These factors are:
How & Where Constructor Code Transform/Synthesize With Inheritance & Composition Class?
Mode of inheritance (virtclass Foo
{
public:
Foo(){cout<<"Foo"<<endl;}
~Foo(){cout<<"~Foo"<<endl;}
};
class base
{
public:
base(){cout<<"base"<<endl;}
~base(){cout<<"~base"<<endl;}
};
class Bar /* : public base */
{
Foo foo;
char *str;
public:
Bar()
{
cout<<"Bar"<<endl;
str = 0;
}
~Bar(){cout<<"~Bar"<<endl;}
};
Bar::Bar()
{
foo.Foo::Foo(); // augmented compiler code
cout<<"Bar"<<endl; // explicit user code
str = 0; // explicit user code
}
How & Where Destructor Code Transform/Synthesize With Inheritance & Composition Class?