Index

C & C++ Programming - Polymorphism

#pragma once

class CBase
{
public:
  CBase();
  virtual ~CBase();
};

#pragma once

class CDerived : public CBase
{
  public:
  CDerived();
  ~CDerived();
};

void UnawareofDerived(CBase *objBase);

void UnawareofDerived1(CDerived *objDerived);

#include "stdafx.h"
#include "base.h"

CBase::CBase()
{
  cout << "Base CTOR\n";
}

CBase::~CBase()
{
  cout << "Base DTOR\n";
}

CDerived::CDerived()
{
  cout << "Derived CTOR\n";
}

CDerived::~CDerived()
{   cout << "Derived DTOR\n";
}

void UnawareofDerived(CBase *objBase)
{
  delete objBase;
}

void UnawareofDerived1(CDerived *objDerived)
{
  delete objDerived;
}

/////////////////////////////////////////////////////////////////////////
// Finds the size of objects - DIAMOND INHERITANCE
#pragma once

#include "iostream"
using namespace std;

class CBaseSz // 4 Because of virtual function
{
public:
  CBaseSz() {}

  // Size of Empty class = 1
  // For any number of function class object size will remain 1
  // Any static function also doesnot contribute to the size of object
  // Size of class increases as the members are added
  // For any virtual object added class size becomes 4
protected:
 //int data;
 virtual void Print()
  {
    cout << "I am in base class" << endl;
  }
};

class CDerivedSz1 : virtual public CBaseSz // 4 (virtual Function) + 4 (V-Table)
{
protected:
 //int data1;
};

class CDerivedSz2 : virtual public CBaseSz // 4 (virtual Function) + 4 (V-Table)
{
protected:
 //int data2;
};

class CDerivedSz3 : public CDerivedSz1, public CDerivedSz2 // 4 (virtual Function)
     // + 4 (virtual Class) X 2
{
protected:
  //int data3;

 // Re-defining the virtual function here doesn't contribute to size of class
  void Print()
 {
   cout << "I am in derived class" << endl;
  }

 // virtual func() {} will added 4 in the size
};

struct User{
};

void Test1()
{
  cout << "1\n";
 CBase *p_objBase = new CDerived();

  UnawareofDerived(p_objBase);// If the base class DTOR isn't made virtual then
  // in the above case derive class DTOR will not be
 // called. Could result in serious error.

  cout << "2\n";
  CDerived *p_objDerived = new CDerived();

  UnawareofDerived(p_objDerived); // UPCASTING here derived class object knows abt
  // Base class.

  cout << "3\n";
  // CDerived *p_objDerived = new CBase(); Not possible DOWNCASTING

  cout << "4\n";
  CDerived l_objDerived ;
}

void TestSz()
{
  class CBaseSz b;
  CDerivedSz1 d1;
  CDerivedSz2 d2;
  CDerivedSz3 d3;

 // Calculating the sizeof each object
  // If a class is Virtually Inherited 4 Byte of addition space is allocated for the   V-TABLE
  cout << sizeof(b) << endl << sizeof(d1) << endl << sizeof(d2) << endl
  << sizeof(d3) << endl;

  struct User sA, sB;

  cout << &sA << "\t" << &sB << endl;
  if (&sA == &sB) {
  cout << "Same Address\n";
  }
}

Index