-4

I have class A and class B, and I created in class B object class A. My question is how to copy object class A in class B by using instructor copy?

class B {
    A *obj;
    unsigned short room;
    unsigned short area;
public:
    B();
    B(const B&);
    ~B();
    void setRoom(unsigned short);
    void setArea(unsigned short);
    unsigned short getRoom() { return room; };
    unsigned short getArea() { return area; };
};

And here is instructor copy:

B::B(const B&p)
{
    room = p.room;
    area = p.area;
    // A = ?!
}

Another question: How to set and get object A in class B?

//void setObj(A*);?
// A* getObj():?

Thanks

Oleg Grytsenko
  • 242
  • 1
  • 3
  • 8
  • You did not "create in class B object class A". The only thing that class A contains is a pointer to an indeterminate number of instances of class B. – Sam Varshavchik May 29 '16 at 14:56

2 Answers2

4

If A has a copy constructor, you can just do:

B::B(const B& p)
{
    room = p.room;
    area = p.area;
    obj = new A(*(p.obj));
}

Preferably:

B::B(const B& p) : 
    obj(new A(*(p.obj))), room(p.room), area(p.area)
{ }

And I hope your destructor ~B(); deletes obj?

B::~B()
{
    delete obj;
}

Read up on Rule of Three And Rule-of-Three becomes Rule-of-Five with C++11?

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
1
How to set and get object A in class B?

Set the object by using the following format.

void B::setAObj(A *aobj)
{
obj = aobj;
}

get the object by using the following

A* B::getAobj()
{
return obj;
}
VINOTH ENERGETIC
  • 1,775
  • 4
  • 23
  • 38