On Aug 5, 3:26 am, "Jim Langston" <tazmas...@rocketmail.com> wrote:
"gccntn" <gcc...@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?- Hide quoted
text -
- Show quoted text -
"The main quesiton is, WHY does B need to call a method of C?"
Good question. Say A (the composite class) is Car, B is Controls and C
is Engine. As I envision this, Controls must be able to tell Engine
when to Start, Accelerate, Stop and so on. However, please let me know
if anybody wants to suggest a different design. I'm open to
suggestions.
Thanks for all the good tips.
A car HAS controls. Being such, C should be inside B.
I would go with method 3. B has it's own C.