Construct an object from its base

Hi,

I have this situation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Base {
private:
  map<UINT, string> m_MyMap;
  string m_MyString;

public:
  Base() {};
  
  Base(string str) { 
    ParseString(str); 
  }

  void ParseString(string& str) {
     //...populare map
  }
};


class Derived : public Base {
public:
  Derived(string str) : Base(str) {};

};


Now, I'm searching for a way to create a Derived object from the Base (best without calling ParseString() but using the map directly), something like:

1
2
Base BaseObj("bla bla");
Derived dev(BaseObj);


or

1
2
Base BaseObj("bla bla");
Derived dev = BaseObj;


How can I do it?

Regards,
Daniele.
Sounds like you're trying to create a constructor for the derived class

1
2
3
4
Derived::Derived(Base  someBaseObject)
{
// code in here to copy the fields you want to copy
  }

What Moschops said, you will also want to write a copy constructor for the Base class. If you want to do it right, using the member initialize list
You dont have to do any thing at all, your sub-class constructor does the work for you already, whenever you create a new object of sub-class, that is the way it works:-)

Derived(string str) : Base(str) {}; dont you see ? your sub-class call the constructor of your super-class...

you create an object like this Derived dev ("bla bla"); that is all
Last edited on
Hi guys,

thanks for your replies!
Yes, at the end, I need to write a copy constructor but, writing it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Base {
private:
  map<UINT, string> m_MyMap;
  string m_MyString;

public:
  Base() {};
  
  Base(string str) { 
    ParseString(str); 
  }

  void ParseString(string& str) {
     //...populare map
  }

  string ToString() { return m_MyString; }
};


class Derived : public Base {
public:
  Derived(string str) : Base(str) {};

  Derived(const Base& obj) {
    Base::ParseString( obj.ToString(); }
  }
};


I get an error: unable to cast 'this' from Base to Base& loss qualifier.

Another alternative is to write also an operator=() overload marking m_MyMap as protected...

1
2
3
4
5
Derived& operator=(const Base& obj) {
  if (this != &obj) {
    m_MyMap = obj.m_MyMap;
  }
}


As I said in my previous post, I need to construct (or assign) the Derived object from a (already) constructed Base object.

Cheers,
Daniele.
What about just

 
Derived(const Base& obj) : Base(obj) { }


this uses the copy constructor in Base to initialize the base part
Topic archived. No new replies allowed.