Re: Aggregation order call
On Jul 23, 11:19 am, sreeni <sreeni.h...@gmail.com> wrote:
I have a similar class hierarchy
class Base
Rename to "base" to make this compile.
{
public:
virtual get_method1();
virtual get_method2();
}
You forgot the return type, the virtual destructor (see <http://
www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7>), and
a semicolon after the class. And likewise throughout.
class derived1 :public base
{
public:
friend class derived2;
This friend is unnecessary. All functions are public. Cf. <http://
www.parashift.com/c++-faq-lite/friends.html#faq-14.1>.
virtual get_method1();
virtual get_method2();
void method(); // internally calls get_method1();get_method2()
I presume you meant that it calls them without qualification, e.g.,
void method()
{
get_method1();
get_method2();
}
}
class derived3:public base
{
public:
virtual get_method1();
virtual get_method2();
}
class derived2 : public derived3
{
public:
virtual get_method();
I presume you meant "get_method1();"
virtual get_method2();
private :
derived1* p;
}
i have to handle two scenarios
i ) i need to call derived1 function method from derived2 through
pointer p this can be achieved with current setup
p->method() which internally would call get_method1() and
get_method2() of derived1
Alternately, you could call p->get_method1() and p->get_method2()
directly since they're public.
ii) i need to call derived1 function method from derived2 through
pointer p
but method() of derived1 should call get_method1() and get_method2()
of derived2 obj
Not as written. Your derived1 has no access to an *instance* of
derived2 whatsoever (the friend statement does nothing in this
respect).
You could rewrite derived1's method() function something like this:
class derived1 : public base
{
// ...
void method( base* b )
{
b->get_method1();
b->get_method2();
}
};
Then when you want derived1's virtual functions, send in a pointer to
a derived1 instance, and likewise with a derived2 instance:
void derived2::my_func()
{
p->method( p ); // calls derived1 functions
p->method( this ); // calls derived2 functions
}
(You could also make derived1::method() static in my implementation
since it doesn't access local variables, but in that case, it should
probably be pulled out of the class altogether.)
However, I suspect that this code displays a misunderstanding of
polymorphism and how classes are supposed to work. See these FAQs on
inheritance:
http://www.parashift.com/c++-faq-lite/virtual-functions.html
http://www.parashift.com/c++-faq-lite/proper-inheritance.html
http://www.parashift.com/c++-faq-lite/abcs.html
and/or a good C++ book (_Accelerated C++_ by Koenig and Moo, for
instance).
Cheers! --M