I made a class A and a class B. Then created an object of class A using a pointer of A.
Then I gave ->
B* bptr = (B*) aptr;
When I call functions of class B using the bptr, it calls the function.
But during the whole execution, it never calls the constructor of type B.
Then how can it call the function from B class?
What is the mechanism behind this?
How is the variable in class B initialized with some value in class A? And since it is calling functions and initializing variable in class B, it should have constructed an object of this class?? (am I right...?)
Expand|Select|Wrap|Line Numbers
- class A{
- public:
- int j;
- A()
- {
- printf("Inside A constructor.\n");
- j=20;
- }
- ~A() {}
- };
- class B{
- public:
- int i;
- int k;
- char c;
- B() {printf("Inside B default constructor.\n");}
- B(A a)
- {
- printf("Inside B constructor.\n");
- c='c';
- i = 10;
- k=100;
- }
- ~B(){}
- void fun()
- {
- printf("Inside fun\n");
- printf("i = %d\n", i);
- printf("k = %d\n", k);
- }
- };
- int main()
- {
- A* aptr = new A();
- B* bptr = (B*) aptr;
- bptr->fun();
- return 0;
- }