Pointer to derived without virtual
// Ptrtoderived.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
class B
{
int i;
public:
void Set_i(int a)
{
i=a;
}
int get_i()
{return i;}
};
class D : public B
{
int j;
public:
void set_j(int a)
{
j=a;
}
int get_j()
{
return j;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
B *b_ptr;
D d_obj;
D d_o[2];
// base ptr can hold derived obj and only can access base members
// if Base ptr holds base obj then also same as can access base members only
b_ptr = &d_obj;
b_ptr->Set_i(20);
((D *)b_ptr)->set_j(56); // casting a base pointer to derived
// once increment base poinetr then its will point to the base class not derived one.
b_ptr = d_o;
d_o[0].Set_i(100);
d_o[1].Set_i(200);
int temp = b_ptr->get_i();
b_ptr++;
temp = b_ptr->get_i(); // Garbage value
D *d_ptr;
// derived pointer can hold derived obj can access both base & derived members
d_ptr = &d_obj;
d_ptr->Set_i(65);
d_ptr->set_j(544);
B b_obj;
d_ptr = static_cast<D*>(&b_obj); // static cast can access the both base & derived class members
//d_ptr = dynamic_cast<D*>(&b_obj); // dynamic cast cant cast
d_ptr->Set_i(25);
d_ptr->set_j(98);
return 0;
}
//
#include "stdafx.h"
#include <iostream>
class B
{
int i;
public:
void Set_i(int a)
{
i=a;
}
int get_i()
{return i;}
};
class D : public B
{
int j;
public:
void set_j(int a)
{
j=a;
}
int get_j()
{
return j;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
B *b_ptr;
D d_obj;
D d_o[2];
// base ptr can hold derived obj and only can access base members
// if Base ptr holds base obj then also same as can access base members only
b_ptr = &d_obj;
b_ptr->Set_i(20);
((D *)b_ptr)->set_j(56); // casting a base pointer to derived
// once increment base poinetr then its will point to the base class not derived one.
b_ptr = d_o;
d_o[0].Set_i(100);
d_o[1].Set_i(200);
int temp = b_ptr->get_i();
b_ptr++;
temp = b_ptr->get_i(); // Garbage value
D *d_ptr;
// derived pointer can hold derived obj can access both base & derived members
d_ptr = &d_obj;
d_ptr->Set_i(65);
d_ptr->set_j(544);
B b_obj;
d_ptr = static_cast<D*>(&b_obj); // static cast can access the both base & derived class members
//d_ptr = dynamic_cast<D*>(&b_obj); // dynamic cast cant cast
d_ptr->Set_i(25);
d_ptr->set_j(98);
return 0;
}
Comments
Post a Comment