Skip to content

CPP Common Knowledge notes!!



class TestCode
{
//This is a test for Syntax highlighter!!!
};

Item #11 : Compiler puts stuff in classes.
Compiler puts a virtual function table ptr in each class object with virtual functions.
Virtual function table pointer not same across platforms!!
Compiler may not put all these extra constructs in a struct.
Virtual inheritance is required when the diamond inheritance is causing issues.
For example:

class Base
{
public:
virtual void foo();
};

class D1 : public virtual Base
{
public:
void foo2();
};

class D2 : public virtual Base
{
public:
void foo3();
};

class SD : public D1, public D2
{
// We have taken care of the diamond inheritance issue with the virtual keyword
// so compiler is gonna shut up now!!
};

Item #12 : Assignment & initialization are different.
These two ops not so diff in built-in types like int, char etc.
For user-defined types, it would not be advisable to perform user-defined assignment.


class X
{
char* buf;
mutable bool modified;
Y obj;
public:X()
{
buf = new char[100];
for(int i = 0;i<100;i++) 
modified = false;
if( < 98)
return;
buf[index] = c;
modified = true;
}

void printdata()
{
cout << "Data is "<<; 
ptr =static_cast(::operator new(sizeof(X)+100));// X::buf is not init!!
ptr->setData(0,'c');
}

Item #13 : Copy operations.
Copy construction and copy assignment are different operations.

class Hoo
{ 
char* buf; 
int size;
public: 
//copy CTor 
Hoo() 
{  
buf = 0x00;  
size = 0x00; 
}

 ~Hoo() 
{  
if(buf)  
{   
delete[] buf;   
buf = NULL;  
}  
size = 0x00; 
}

 void setData(char* data, int asize) 
{  
size = asize;  
buf = new char[size + 1];  
memset(buf, 0x00, size+1);  
strncpy(buf, data, size); 
}

 Hoo(Hoo const &amp; hoo) 
{ 
 setData(hoo.getBuf(), hoo.getSize()); 
}

 Hoo& operator= (Hoo const &hoo) 
{  
if(this != &hoo)  
{   
if(buf)   
{    
delete[] buf;    
buf = NULL;   
}   
size = 0x00;   
setData(hoo.getBuf(), hoo.getSize());  
}  
return *this; 
}

 char* getBuf() const 
{ 
return buf;
}

 int getSize() const { return size;}

};

void copy_ctor_assgn()
{
Hoo data;
data.setData("Hello",5);
Hoo dat2(data);
//copy ctor invoked here
Hoo dat3;
dat3 = dat2;// assgn operator invoked here
}

Item #14 :Function Pointers.
Legal to point to inline functions, but the resultant call will not be inline.The compiler will not be able to determine at compile time what function is being called.
Can also point to an overloaded function. The particular function called will depend on the match between the function ptr type and the overloaded functions.