Re: Composite classes
"gccntn" <gccntn@yahoo.com> wrote in message
news:1186289843.767046.204180@k79g2000hse.googlegroups.com...
I have a basic C++ question. Consider a composite class A containing
two data members B and C that are also class objects:
class A
{
private:
B objB; // B is a class
C objC; // C is class
public:
...etc...
}
Is there a way for objB to invoke a method defined in class C? For
instance,
void B::functionB(void)
{
objC.functionC(void);
}
What is the best way to "link" B and C?
It depends on what it is you are actually trying to achieve. If B needs to
invoke a method of C, then perhaps C should be a member of B. You have many
alternatives though.
( following is all untested code )
1. Have the constructor of B take a reference to C and store it.
class B
{
public:
B( C& c ): c(c) {}
void functionB();
private:
C& c;
}
void B::functionB()
{
c.functionC();
}
2. Have an initialization function for B take a pointer to C and store it.
class B
{
public:
B( ): c( NULL ) {}
void Init( C* cp ) { c = cp; }
void functionB();
private:
C* c;
}
void B::functionB()
{
if ( c )
c->functionC();
}
3. Best IMO, have B create it's own C
class B
{
public:
void functionB();
private:
C c;
}
void B::functionB()
{
c.functionC();
}
4. Have functionB accept a reference to C.
class B
{
public:
void functionB( C& c);
}
void B::functionB( C& c )
{
c.functionC();
}
5. Other less desirable methods (public instance of C, etc..)
The main quesiton is, WHY does B need to call a method of C?