473,466 Members | 1,301 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

define a copy constructor in a class having data member as an object of another class

Hi,
can anyone help me by writing a sample code of defining a copy
constructor in a class having data member as an object of another
class.
for eg:
class A{
int x;
public: A(){ x=6;}
};

class B{
A a1;
public:B(B &b1)
{ ???} //how i can assign the data members??
};

Any idea ...Thanks

Nov 9 '06 #1
11 1929
VJ
da*******@gmail.com wrote:
Hi,
can anyone help me by writing a sample code of defining a copy
constructor in a class having data member as an object of another
class.
for eg:
class A{
int x;
public: A(){ x=6;}
};

class B{
A a1;
public:B(B &b1)
{ ???} //how i can assign the data members??
};

Any idea ...Thanks
1) add a public method to class A to assign a value to x
2) make class B friend of class A
Nov 9 '06 #2
da*******@gmail.com wrote:
can anyone help me by writing a sample code of defining a copy
constructor in a class having data member as an object of another
class.
for eg:
class A{
int x;
public: A(){ x=6;}
};

class B{
A a1;
public:B(B &b1)
{ ???} //how i can assign the data members??
};
Like so:

class B
{
public:
B( B& b1 )
: a1( b1.a1 )
{
}
};

Greg

Nov 9 '06 #3
da*******@gmail.com wrote:
Hi,
can anyone help me by writing a sample code of defining a copy
constructor in a class having data member as an object of another
class.
for eg:
class A{
int x;
public: A(){ x=6;}
};

class B{
A a1;
public:B(B &b1)
{ ???} //how i can assign the data members??
};
Like so:

class B
{
A a1;

public:
B( B& b1 ) : a1( b1.a1 )
{ }
};

Greg

Nov 9 '06 #4
thanks,

if the situation is so:
class B{
A *a1;
public:
B(B &b1){???}

Nov 9 '06 #5
da*******@gmail.com wrote:
thanks,

if the situation is so:
class B{
A *a1;
public:
B(B &b1){???}
Pretty much as one might expect:

class B
{
A *a1;
public:
B( B& b1)
{
a1 = b1.a1;
}
};

Note that "a1", even as a pointer member, can still be initialized the
same way as before (in the member list initializer of the contructor)
instead of within the body of B's construtor - as shown here.

When possible, it's better to initialize a class member in the
constructor's member-initializer list than in its body.

Greg

Nov 9 '06 #6
da*******@gmail.com wrote:
thanks,

if the situation is so:
class B{
A *a1;
public:
B(B &b1){???}
This case is trickier since a1 is now a pointer. The question is
whether to make a "deep copy" or a "shallow copy" of B. A deep copy
also creates a copy of the A object that a1 points to - and then
assigns the copied A object's address to the a1 member pointer in B's
copy. A shallow copy would just copy the a1 pointer itself - meaning
that both the original and copied B object would each have an a1 member
pointing to the same A object - which can be a problem if B is supposed
to delete the A object at some point (more on that problem later).

In terms of advantages, though, a shallow copy is more efficient and
economical than making a deep copy. Furthermore, a shallow copy of B
looks easy enough to implement:

class B
{
A *a1;
public:
B( B& b1)
{
a1 = b1.a1;
}
};

....but as mentioned above can be very difficult to maintain correctly,
now that a1 is shared. So to manage a shallow copy safely, B should
turn its a1 member into a "smart pointer" such as
std::tr1::shared_ptr<A>.

Note that "a1", even as a pointer member, can still be initialized the
same way as before (in the member list initializer of the constructor)
instead of within the body of B's constructor - as shown here. When
possible, it's better to initialize a class member in the constructor's
member-initializer list than in its body.

Greg

Nov 9 '06 #7
Thanks Greg, its a wonderful explanation..

its fine in compiling and linking the program in case of shallow copy u
provided
class B
{
A *a1;
public:
B( B& b1)
{
a1 = b1.a1;
}
};
but when i try to run it ends with some memory unhandled exception, its
perhaps due to shallow copy where it only copies the memory address not
the corresponding value.

ok then i hope the correct answer for tthe problem is to make it a deep
copy. could u please add some more lines in the above code so that the
output will be ok.

Nov 9 '06 #8
da*******@gmail.com wrote:
Thanks Greg, its a wonderful explanation..

its fine in compiling and linking the program in case of shallow copy u
provided
class B
> {
A *a1;
public:
B( B& b1)
{
a1 = b1.a1;
}
};

but when i try to run it ends with some memory unhandled exception, its
perhaps due to shallow copy where it only copies the memory address not
the corresponding value.

ok then i hope the correct answer for tthe problem is to make it a deep
copy. could u please add some more lines in the above code so that the
output will be ok.
We can't answer your question without knowing what A is, and how a1
was set initially. Most likely your problem is less with the shallow
copy, but more with the fact that the object pointed by a1 is
mismanaged (deleted twice, deleted while people are still using it,
etc...).

Further the rule of three applies very much here. If you need to
define a copy constructor, a copy-assignment operator, or a destructor,
you probably need to define all three.

Nov 9 '06 #9
HI I have already define A in the begining of the thread, anyway A is a
class and here is the defn:
class A{
int x;
public: A(){ x=6;}
};

how to ensure that if i write overloaded assignment op and destructor
here then evrything will be fine...:)

Ron Natalie wrote:
da*******@gmail.com wrote:
Thanks Greg, its a wonderful explanation..

its fine in compiling and linking the program in case of shallow copy u
provided
class B
{
A *a1;
public:
B( B& b1)
{
a1 = b1.a1;
}
};
but when i try to run it ends with some memory unhandled exception, its
perhaps due to shallow copy where it only copies the memory address not
the corresponding value.

ok then i hope the correct answer for tthe problem is to make it a deep
copy. could u please add some more lines in the above code so that the
output will be ok.
We can't answer your question without knowing what A is, and how a1
was set initially. Most likely your problem is less with the shallow
copy, but more with the fact that the object pointed by a1 is
mismanaged (deleted twice, deleted while people are still using it,
etc...).

Further the rule of three applies very much here. If you need to
define a copy constructor, a copy-assignment operator, or a destructor,
you probably need to define all three.
Nov 9 '06 #10
LR
da*******@gmail.com wrote:

[Please do not top post, content moved]
Ron Natalie wrote:
>>da*******@gmail.com wrote:
>>>Thanks Greg, its a wonderful explanation..

its fine in compiling and linking the program in case of shallow copy u
provided
class B

{
A *a1;
public:
B( B& b1)
{
a1 = b1.a1;
}
};
but when i try to run it ends with some memory unhandled exception, its
perhaps due to shallow copy where it only copies the memory address not
the corresponding value.

ok then i hope the correct answer for tthe problem is to make it a deep
copy. could u please add some more lines in the above code so that the
output will be ok.

We can't answer your question without knowing what A is, and how a1
was set initially. Most likely your problem is less with the shallow
copy, but more with the fact that the object pointed by a1 is
mismanaged (deleted twice, deleted while people are still using it,
etc...).

Further the rule of three applies very much here. If you need to
define a copy constructor, a copy-assignment operator, or a destructor,
you probably need to define all three.


HI I have already define A in the begining of the thread, anyway A is a
class and here is the defn:
class A{
int x;
public: A(){ x=6;}
};

how to ensure that if i write overloaded assignment op and destructor
here then evrything will be fine...:)
Depends on what you want them to do.

Heres one way.

class A {
int x;
public:
void swap(A &a) {
std::swap(a.x,x);
}
A() : x(6) {}
// note const A & in copy ctor
A(const A &a) : x(a.x) {}
A &operator=(const A &a) {
// see gotw for assigment ops
A temp(a);
swap(temp);
return *this;
}
};

class B {
std::auto_ptr<Aa1;
public:
void swap(B &b) {
// swap pointers, not instances
std::swap(a1,b.a1);
}
B() : a1() {}
B(const B &b) : a1( b.a1.get() ? new A(*b.a1.get()) : 0 ) {}
B &operator=(const B &b) {
B temp(b);
swap(temp);
return *this;
}
};
Now, if you have to use a raw pointer, then you can back out of this, by
replacing std::auto_ptr and creating your own destructor for class B,
where you will have to delete the thing the pointer is pointing to.
Nov 9 '06 #11
da*******@gmail.com wrote:
HI I have already define A in the begining of the thread, anyway A is a
class and here is the defn:
class A{
int x;
public: A(){ x=6;}
};

how to ensure that if i write overloaded assignment op and destructor
here then evrything will be fine...:)
You haven't answered the question of how B::a1 gets set to anything.
Nov 9 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

42
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same...
2
by: Birt | last post by:
My understanding about defining your own copy and assignment constructors is whenever there is a member of pointer type. Is this true or is there any exception to this"rule"? How about when you...
8
by: trying_to_learn | last post by:
Why do we need to explicitly call the copy constructor and the operator = , for base class and member objects in composition? ....book says "You must explicitly call the GameBoard copy-constructor...
5
by: Martijn van Buul | last post by:
Hi. I'm having a peculiar problem at work. I've been googling for it, but haven't found an authorative answer. In a nutshell (Long story follows), what I'd like to know is: If I have a C++...
8
by: rKrishna | last post by:
I was trying to understand the real need for copy constructors. From literature, the main reason for redfinition of copy constructor in a program is to allow deep copying; meaning ability to make...
13
by: blangela | last post by:
I have decided (see earlier post) to paste my Word doc here so that it will be simpler for people to provide feedback (by directly inserting their comments in the post). I will post it in 3 parts...
1
by: blangela | last post by:
3.0 Advanced Topic Addendum There are a few cases where the C++ compiler cannot provide an overloaded assignment operator for your class. If your class contains a const member or/and a...
13
by: JD | last post by:
Hi, My associate has written a copy constructor for a class. Now I need to add an operator = to the class. Is there a way to do it without change her code (copy constructor) at all? Your help...
34
by: =?ISO-8859-1?Q?Marcel_M=FCller?= | last post by:
Hi, is there a way to avoid the automatic copy constructor generation. I do not want the object to be non-copyable. I simply do not want that copying is done by the default copy constructor. But...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.