Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising classes inside another class in C++?

I have this definition in a header file:

class Owner
{
private:
    // Fields
    Child* _myChild1;
public:
    // Constructors
    Owner();
    Owner(const char childName[]);
};

and this implementation:

Owner::Owner(const char childName[])
{
//do some operations - children must be created after these ops
_myChild = new Child(childName);
}

and this main() function:

int main()
{
Owner("child1"); 
}

Some questions, and please bear with me here, I'm just starting out with C++ ..

  • Given that the child classes are known at compile time am I right in thinking that I don't need to create them with 'new' on the heap? If so how? I have tried using this syntax in the Owner implementation but the compiler moans ('term does not evaluate to a function..'):

_myChild(childName);

  • However, using this syntax in the implementation is ok, why?

Child _myChild(childName);

  • Is the paradigm that I'm using correct? In other words, as a general rule, if one class wraps another does the owner only ever hold pointers to the classes it wraps?
  • How would you more experienced guys do it?

Thanks for any advice..

like image 756
jamieQ Avatar asked Dec 14 '22 01:12

jamieQ


1 Answers

Like this:

class Owner
{
    private:        // Fields
        Child   _myChild1;
    public:        // Constructors
        Owner();
        Owner(const char childName[]);
};

Owner::Owner()
    :_myChild1("Default Name")
{}

Owner::Owner(const char childName[])
    :_myChild1(childName)
{}

// Without more info about what you are doing it is hard to tell
// But a trivial change could be

Owner::Owner()
// Child defautl constructor called here
{
    // Do processing.
    _myChild1.updateName(name);
}

Owner::Owner(const char childName[])
// Child defautl constructor called here
{
    // Do processing.
    _myChild1.updateName(std::string("X") + childName);
}

The question is what kind of processing do you need done before the child.

As a side not:

  • avoid underscore as the first character in a member name.
    Most of the time it is OK but there are sitations where it is not. So best to just avoid them.
  • Rather than passing an array of characters pass a std::string const&
like image 199
Martin York Avatar answered Jan 05 '23 04:01

Martin York