[C++] Initilizing a member in the header file

I'm having a really dumb moment here. Let's say I have a class "Bar" defined with a constructor as follows:
C++:
class Bar{
private:
    double _value;
public:
    Bar(double value);
}
An instance of this class is member of another class called "Foo":
C++:
class Foo{
private:
    Bar bar;
}
Is there a way to call the custom constructor Bar(double value) without using new? Preferably, I'd like to have the value initialized in the header file of Foo:
C++:
class Foo{
private:
    Bar bar(42.0);
}
But this doesn't seem to be working....
 
I not expert in this code programming, still student from @JB3DG, I try to give a help

C++:
Bar bar;
Foo foo;

class Bar
{
public:
    Bar() { };
    ~Bar() { };

    int var1;
    int var2;

    void Function();
private:

};

class Foo
{
public:
    Foo() { };
    ~Foo() { };

    // identical var from class Bar
    int var1;
    int var2;

    // new var
    int var3;
    int var4;


private:

};


void Bar::Function()
{
    // I use 4 variable from 2 class
    // sample
    var1 = foo.var3;
    foo.var4 = var2 + var1;

    // I usually do this,
    // this function is different var from above.
    bar.var1 = foo.var3;
    foo.var4 = bar.var2 + bar.var1;
    // see the different?

    // you can use identical "var" on different class, but
    // always include class pointer

    foo.var1 = 2 * bar.var2;
    // you can do mixed between class, always remember the pointer
    // etc, etc
}
 
Last edited:

JB3DG

Resource contributor
@cheangjc gave the answer I was going to give. I normally do the constructor body inside the class definition in the header file rather than merely declaring it in the class and adding the body in a cpp file. I do however, define my function bodies and global variables in the cpp file. Headers are otherwise only for cross referencing with other cpps.
 
Oh man, thanks! I feel so dumb once again :oops:

I also found another solution, but I don't know if there's any downsides to it:
Code:
class Foo{
private:
    Bar bar = Bar(42.0);
}
Funny enough, this seems to be working, and since there's no new, I take it that there's no need to delete it. What's nice about this is that I don't need to define a constructor for Foo in this case.

I try to keep my header files clean of ANY implementations, other than some initialization values.
 
I would confirm that bar is being deleted by the code. I have learned through the years to always check, never assume... especially with regards to Microsoft code.
 
Top