Hey, guys I think this is a very simple problem and that I just can't get it is due to some gap in my knowledge. Any way, what is wrong with this :

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

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

//Does not work
class B {A ob(5);};
//Works
main(){A ob(5);}

By does not work, I mean compile.

Thanks up front.

Recommended Answers

All 4 Replies

You should write your B class like this:

class B {
     A *ob;
};

and then in B constructor add ob = new A(5); I think you can't call constructors from within a class declaration.

Hey, thanks for the reply.

What do you mean by
"in B constructor add ob = new A(5);"

What I am trying to do is make several objects of a class with several parameters within another class, which then in return gets called in main.

I don't understand what you are trying to do - but my suggestion was to write a constructor for your B class like this

B::B() {
     ob = new A(5);
}

so that every time an object of type B is created, its member A object will be initialized with the chosen value. Of course you may pass parameters to the constructor of B and forward them to the constructor of A - just don't forget to free the memory by putting delete A; in B's destructor.

Hope this helps.

I think a little care in needed here. Poster #4 suggested making a heap object of A. [new A(5)] but that is maybe not what you want. It adds a level of complexity that might not be needed. You have to delete ob in B's destructor and manage the memory carefully in the copy constructor.

So what about

class A
{
  private: 
    int value;
  public: 
    A(int);        // constructor taking a value
};

class B
{
   private:
       A obj;
  public:
     B();           // Default Constructor
};

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

B::B() : Obj(5)
{}


int
main()
{
  A ob(8);
  B bItem;
}

That way you have a A object in each B, and it goes out of scope on with with the corresponding B object.

It you want to pass parameters to B from A, try this.

class B 
{
 private:
       A obj;
       A secondObj;
  public:
     B(int,int);           // Constructor
};

B::B(int a,int b) : 
   Obj(a),SecondObj(b)

int
main()
{
   B bItem(3,4);       // Make Obj(3) and secondObj(4)
}
commented: you're right, it's probably better in this case. thanks for pointing it out +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.