Taztingo
Taztingo

Reputation: 1945

Initialization of Class' object members in class' method

Is it possible to instantiate object member variables in the class' methods, besides the constructor. I want to do this without using pointers because I'm trying to make my code use more stack memory. (My professor said so)

I have looked this up before, and the closest thing I found was extern. That sounds kind of dirty, and I'm not sure if that's exactly what I'm looking for.

This is what I'm trying to do, and I'm trying to do it without pointers:

class A
{
    private:
        B var;
    public:
        A();
        void setVar();
};

A::A()
{
}

void A::setVar()
{
    var = B(1,2);
}

class B
{
    public:
        B();
        B(int a, int b);
};

B::B()
{
}

B::B(int a, int b)
{
}

Upvotes: 0

Views: 67

Answers (1)

user1118321
user1118321

Reputation: 26345

Member variables that are not pointers will automatically be created on the stack when you create your object on the stack. (That is they'll be part of your object on the stack.) You can initialize them to specific values in the object's constructor in at least 2 ways:

A::A() : var (1,2)
{
}

or

A::A()
{
    var = B (1,2);
}

Upvotes: 2

Related Questions