views:

187

answers:

4

Hello, I'm pretty sure that this question is very noob but I'm not used to C++.

I have a .hpp for class definition and a .cpp for class implementation. I have some private instances on the class, for example:

class Test
{
    Test(void);

    private:
        SomeClass anInstance;
};

To create the instance and call the constructor do I must define it again at the constructor of the class?

Test::Test(void)
{
    SomeClass anInstance(constructor parameters);
}

Thanks in advance!

EDIT:

Mmmm, sorry but I don't catch what you're talking about so let me show you a better example:

class A
{
    public:
        A(int p1,int p2);
}

class B
{
    public:
        B(A *p1,int p2);
}

class C
{
    public:
        C(void);
    private:
        A instanceA;
        B instanceB;
}

Then, at the implementation of the constructor of the class C I want to create instanceA and pass it to the constructor of instanceB. Hope this clarifies the question.

+2  A: 

No, class members will be initialized automatically when you Class is constructed. The default (zero-argument) constructor will run.

If there is no such constructor, you need to make an explicit call, from your class' constructor's initialization list:

Class::Class()
: anInstance(4711, "w00t!")
{
}

The initialization list is the code between the colon and the opening brace; it's where you initialize the instance's members. This code runs before the code within the braces.

unwind
Ok, I will check what Initialization List means to see if this gives me some light. Thanks.
SoMoS
+4  A: 

No, you need an initialisation list:

Test::Test(void) : anInstance( parameters)
{
}

This will work well for fixed parameters, like "foobar" or 42, but if you need to pass variable parameters in, you also need to change the Test constructor definition (and the declaration in the header). For example, iif it takes an int to initialise the instance, you need:

Test::Test( int someval ) : anInstance( someval )
{
}

Edit: To do what you are asking about in your edit, you may be better off creating the objects dynamically and using pointers. However, you can do it with values too (using a struct to minimise my typing effort):

struct C {

    int a;
    int b;

    C() : a(1), b(a) {
    }
};

If you do this, note that the initialisation order is the order the member variables appear in the class/struct, not the order in the initialisation list.

anon
This has been the answer that has helped me more. Thanks!
SoMoS
+1  A: 

First, you don't need the void in the declaration of the constructor of Test.

If SomeClass has some parameters to be passed to, you can pass them like this:

Test::Test() : anInstance(params)
{

}
Mike
A: 

If you don't don anything with the SomeClass object, default constructor of SomeClass will called. If you wish to to call it with specific arguments, you need to pass arguments like this:

Test::Test(void) : anInstance(arg1, arg2, ..) {}
gruszczy