Derived copy constructor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Base {
  ...  //  No copy constructor
};


class Derived: public Base
{
  ...
  public:
	Derived(const Derived& source);
  ...
};

Derived::Derived(const Derived& source)
{
	if (this != &source)
	{
		//  copy Derived members
	}
}


In class Base, I did not build a copy constructor. Please tell me if it is possible to copy all the member of class Base in the copy constructor of class Derived without modifying class Base?

Thanks for your help.
Last edited on
Is this what you want?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Base {
	member1,member2;
};


class Derived: public Base
{
	member3;
  public:
	Derived(const Derived& source);
};

Derived::Derived(const Derived& source)
{
	if (this != &source)
	{
		member1=source.member1;
		member2=source.member2;
	}
}

Notice that members of the Base class have to be protected or public
Last edited on
Unless you explicitly declare one, the compiler gives every class a default copy constructor that implements member-wise copy. So the answer to your question is that you do not need to modify Base.

Most likely, you don't even need to declare a copy constructor in Derived either. The only time you need to write a copy constructor is if your class contains pointer members and you need to take "deep" copies (ie, replicate not the pointer, but rather what is being pointed to).
Topic archived. No new replies allowed.