#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
int a,b,c;
A()
{
a=0;
b=0;
c=0;
}
};
class B:public A
{
public:
void get()
{
A *a2 =new A;
a2->a=10;
a2->b=20;
a2->c=30;
cout<<a2->a<<""<<a2->b<<""<<a2->c<<""<<endl;
cout<<"Checking!"<<endl;
}
};
int main()
{
A *a1 = new A;
B *b1 = new B;
cout<<a1->a<<""<<a1->b<<""<<a1->c<<""<<endl;
b1->a=10;
b1->b=20;
b1->c=30;
cout<<b1->a<<""<<b1->b<<""<<b1->c<<""<<endl;
b1->get();//cant able to change the variables of the base class object with the derived class object
cout<<a1->a<<""<<a1->b<<""<<a1->c<<""<<endl;//will print the same values..
//b1->get();
return 0;
}
output:
000 102030 102030 Checking! 000 Press any key to continue . . .
//The address of the variables that is holded by the derived class object is different from the address of the variables that is holded by the base class object.Isnt..
//But is there any possiblity to change the variables of the base class through the derived class object..
In your
get()method, you are actually creating a temporary instance of Baseclass A, which has nothing to do with the class getting derived. Simply removea2from everywhere in yourget()and try it. You will be able to see the changes happening.[Note: Base class object is automatically allocated when derived object is allocated. That means when you do
new B, it will allocate memory forBandA]Edit:
For your question, your
get()should be like this: