class A
/ \
class B1 class B2
All classes have only public members. Class A is publically inherited and contains virtual member functions and non-virtual member functions with default print(cout) statements, class B1 and class B2 has only non-virtual functions, with definition of the virtual functions from class A. I want to know how to access all members of B2 using pointer of B1, which casting could be used. For example,
B2 obj_b2;
B1* b1_ptr=&obj_b2;
// Using b1_ptr, access all members of obj_b2
If yes, then whether this can be extended further into more deep branches like:
class A
/ \
class B1 class B2
/ \ / \
class C1 ... ... ...
(Accessing members of class C1, etc. from second branch)
EDIT 1: Maybe this will help; this is the example that I have written:
#include<iostream>
using namespace std;
class A{
public:
virtual void v_f1(){
cout<<"virtual A::v_f1()\n";
}
void f1(){
cout<<"A::f1()\n";
}
};
class B1 : public A{
public:
virtual void v_f2(){
cout<<"virtual B1::v_f2()\n";
}
void v_f1(){
cout<<"A<-B1::v_f1()\n";
}
void f2(){
cout<<"B1::f2()\n";
}
};
class C1 : public B1{
public:
void v_f2(){
cout<<"B1<-C1::v_f2()\n";
}
void f3(){
cout<<"C1::f3()\n";
}
};
class D : public C1{
public:
void f4(){
cout<<"D::f4()\n";
}
};
class B2 : public A{
public:
void v_f(){
cout<<"A<-B2::v_f()\n";
}
void f5(){
cout<<"B2::f5()\n";
}
};
class C2 : public B2{
public:
void f6(){
cout<<"C2::f6()\n";
}
};
int main(){
C2 c2_obj;
C2* c2_obj_ref=&c2_obj;
D* d_ptr = dynamic_cast<D*>(c2_obj_ref);
// This statement gives segmentation fault,
// if commented out, the code works fine.
d_ptr->v_f();
// These work fine
d_ptr->f();
dynamic_cast<C2*>(d_ptr)->f5();
dynamic_cast<C2*>(d_ptr)->f6();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire