views:

124

answers:

4

Let's say that I have two classes A and B.

class A
{
    private:
        int value;
    public:
        A(int v)
        {
            value = v;
        }
};

class B
{
    private:
        A value;
    public:
        B()
        {
            // Here's my problem
        }

}

I guess it's something basic but I don't know how to call A's constructor.

Also the compiler demands a default constructor for class A. But if A has a default constructor than wouldn't the default constructor be called whenever I declare a variable of type A. Can I still call a constructor after the default constructor has been called? Or can I declare an instance of a class and then call a constructor later?

I think this could be solved using pointers but can that be avoided ?

I know that you can do something like this in C#.

EDIT: I want to do some computations in the constructor and than initialize the classes. I don't know the values beforehand.

Let's say I'm reading the value from a file and then I initialize A accordingly.

A: 

Try:

    B() :
      value(0)
    { 
        // Here's my problem 
    } 
jdv
+3  A: 

You use an initialization list to initialize the member variables.

public:
    B() : value(4) {   // calls A::A(4) for value.
    }
KennyTM
+13  A: 

The term you are looking for is initializer list. It is separated from the constructor body with a colon and determines how the members are initialized. Always prefer initialization to assignment when possible.

class A
{
    int value;

public:

    A(int value) : value(value) {}
};

class B
{
    A a;

public:

    B(int value) : a(value) {}
}

I want to do some computations in the constructor and than initialize the classes. I don't know the values beforehand.

Simply perform the computation in a separate function which you then call in the initializer list.

class B
{
    A a;

    static int some_computation()
    {
        return 42;
    }

public:

    B() : a(some_computation()) {}
}
FredOverflow
Don't you need copy constructor in A for this?
Manoj R
@Manoj: What makes you think so? I don't see any place in my code where an A object is copied.
FredOverflow
Oh yes. Indeed you don't copy constructor. I got little confused at a(some_computation()).
Manoj R
A: 
Manoj R
Thanks this is what I was looking for.
EyyoFyber
Oh my god, this is **SO** not C++! When in Rome, do as the Romans do. Don't use pointers unless you absolutely have to.
FredOverflow
Well, you _can_ do this, but I don't see why you would. If you will always need to store an `A`, use a variable `A a`, not `A* a`. That way you avoid having to allocate an `A` on the heap, which may also incur memory leakage if you forgot to delete it in the destructor. So do as in FredOverflow's answer. It's faster and less error-prone.
gablin