473,830 Members | 2,086 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Operator New help

Hey guys,

Quick question i have this code and what i want to do is create a deep
copy of class B. Now I tried doing this with the new operator and
pointers. Here's is the orignal
---------------- Original Copy-----------------------
#include <iostream>
using namespace std;

class A
{
int n ;
public:
A():n(0)
{
}
A(int x):n(x)
{
n = x;
}

void print()
{ cout << n<<"\n\n";
}


A(const A& objectCopy){

n = objectCopy.n; // copy constructor

}
};

class B
{
A * a;

public:

B(A & x)
{
a = &x; // Here is the problem so I implemented a new
command
}

void print ()
{
a->print();
}
B(const B& copy){ // Class B copy constructor
a = copy.a;

}
const B &operator=(cons t B x){
a = x.a; // Operator
}
B::~B(){
delete a;

}
};
int main()
{

A a(5);
A a1(7);
a1.print();

B b(a1);
b.print();
B c(a);
b.print();
b = c;

b.print();
cout << endl;
int trick;
cin >trick;
return 0;
}

//--------------------End of Orignal Copy-----------------------
----Version altered with new command in class B--------
#include <iostream>
using namespace std;

class A
{
int n ;
public:
A():n(0)
{
}
A(int x):n(x)
{
n = x;
}

void print()
{ cout << n<<"\n\n";
}


A(const A& objectCopy){

n = objectCopy.n; // copy constructor

}
};

class B
{
A * a;

public:

B(A & x)
{
a = new A(x); //New command
}

void print ()
{
a->print();
}
B(const B& copy){ // Class B copy constructor
a = copy.a;

}
const B &operator=(cons t B x){
a = x.a; // Operator
}
B::~B(){
delete a;

}
};
int main()
{

A a(5);
A a1(7);
a1.print();

B b(a1);
b.print();
B c(a);
b.print();
b = c;

b.print();
cout << endl;
int trick;
cin >trick;
return 0;
}

//---------------------------------------------------------------------
Works fine but say if i change main() so it looks like this

------------------ Aletered main -----------------

int main()
{

A a(5);

B b = a;

{

A a1 (7);
B b1 =a1;
b = b1;
}

b.print();
cout << endl;
int trick;
cin >trick;
return 0;
}
--------------------- End of altered main--------------------

I get a bunch of junk so I found out i need to make a deep copy of B.

This is what i came up with

int *p;
p = new int();
*p = a;

I came up with invalid conversion from 'A*' to 'int'. I don't get why
this wouldn't work.
thank you
john
any help would be appreciated.

Mar 29 '07 #1
8 2010

the code in the OP has a number of inconsistantcie s.

john wrote:
Hey guys,

Quick question i have this code and what i want to do is create a deep
copy of class B. Now I tried doing this with the new operator and
pointers. Here's is the orignal
---------------- Original Copy-----------------------
#include <iostream>
using namespace std;

class A
{
int n ;
public:
A():n(0)
The line above is valid - this is better:

A():n()
{
}
A(int x):n(x)
{
n = x;
why make an assignment to what you already initialized it to ?
}

void print()
{ cout << n<<"\n\n";
}

Why provide your own copy constructor ? Is not the one provided by the
compiler good enough here ?
A(const A& objectCopy){

n = objectCopy.n; // copy constructor

}
};

class B
{
A * a;

public:

B(A & x)
{
a = &x; // Here is the problem so I implemented a new
command
}

void print ()
{
a->print();
}
B(const B& copy){ // Class B copy constructor
a = copy.a;
the line above does not make a copy of the object.
>
}
const B &operator=(cons t B x){
a = x.a; // Operator
}
B::~B(){
delete a;
if you delete - make sure you have a correspoinding new.
>
}
};
int main()
{

A a(5);
A a1(7);
a1.print();

B b(a1);
b.print();
B c(a);
b.print();
b = c;

b.print();
cout << endl;
int trick;
cin >trick;
return 0;
}

//--------------------End of Orignal Copy-----------------------
----Version altered with new command in class B--------
#include <iostream>
using namespace std;

class A
{
.... see earlier commens
};

class B
{
A * a;

public:

B(A & x)
B( const A & x )
{
a = new A(x); //New command
better
>

}

void print ()
{
a->print();
}
B(const B& copy){ // Class B copy constructor
a = copy.a;
// try this one
B(const B& copy) a( new A(* copy.a) ){}
>
}
const B &operator=(cons t B x){
a = x.a; // Operator
delete a;
a = new A(* copy.a);
}
B::~B(){
delete a;

}
};
int main()
{

A a(5);
A a1(7);
a1.print();

B b(a1);
b.print();
B c(a);
b.print();
b = c;

b.print();
cout << endl;
int trick;
cin >trick;
return 0;
}

//---------------------------------------------------------------------
Works fine but say if i change main() so it looks like this

------------------ Aletered main -----------------

int main()
{

A a(5);

B b = a;

{

A a1 (7);
B b1 =a1;
b = b1;
}

b.print();
cout << endl;
int trick;
cin >trick;
return 0;
}
--------------------- End of altered main--------------------

I get a bunch of junk so I found out i need to make a deep copy of B.
That's expected....
....
any help would be appreciated.
Hope it helps...
Mar 29 '07 #2
Gianni Mariani wrote:
>
the code in the OP has a number of inconsistantcie s.
>>
---------------- Original Copy-----------------------
#include <iostream>
using namespace std;

class A
{
int n ;
public:
A():n(0)

The line above is valid - this is better:

A():n()
> {
}
Why is that better? Granted they do the same thing, but the 0 seems
more transparent.
Mar 30 '07 #3

"Mark P" <us****@fall200 5REMOVE.fastmai lCAPS.fmwrote in message
news:jt******** *********@newss vr23.news.prodi gy.net...
Gianni Mariani wrote:
>>
the code in the OP has a number of inconsistantcie s.
>>>
---------------- Original Copy-----------------------
#include <iostream>
using namespace std;

class A
{
int n ;
public:
A():n(0)

The line above is valid - this is better:

A():n()
>> {
}

Why is that better? Granted they do the same thing, but the 0 seems more
transparent.
If the type of 'n' is later changed to some other
type where 0 is not a valid initializer, the syntax
n() will still cause 'n' to be default constructed,
and in the case of scalar types, still initialized to zero.

-Mike
Mar 30 '07 #4
#include <iostream>
using namespace std;

class A
{
int n ;
public:
A():n(0)
{
}
A(int x):n(x)
{
n = x;
}

void print()
{ cout << n<<"\n\n";
}


A(const A& objectCopy){

n = objectCopy.n; // copy constructor

}
};

class B
{
A * a;

public:

B(A & x)
{
a = new A(x);
// x.operator=(x);

}

void print ()
{
a->print();
}


// try this one
B(const B& copy) a( new A(* copy.a) ){
}
const B &operator=(cons t B x){
a = x.a; // Operator

delete a;
a = new A(* copy.a);
};
//---------------------------------------------------------------------------
int main()
{

A a(5);

B b = a;

{

A a1 (7);
B b1 =a1;
b = b1;
}

b.print();
cout << endl;
int trick;
cin >trick;
return 0;
}

---------------------------------------
I changes the code to the following, and their is a parse error?

in the line
B(const B& copy) a( new A(* copy.a) )

B and a are both making a copy??

Mar 30 '07 #5
On Mar 29, 4:12 pm, Gianni Mariani <gi3nos...@mari ani.wswrote:
the code in the OP has a number of inconsistantcie s.

john wrote:
Hey guys,
Quick question i have this code and what i want to do is create a deep
copy of class B. Now I tried doing this with the new operator and
pointers. Here's is the orignal
---------------- Original Copy-----------------------
#include <iostream>
using namespace std;
class A
{
int n ;
public:
A():n(0)

The line above is valid - this is better:

A():n()
{
}
A(int x):n(x)
{
n = x;

why make an assignment to what you already initialized it to ?
}
void print()
{ cout << n<<"\n\n";
}

Why provide your own copy constructor ? Is not the one provided by the
compiler good enough here ?


A(const A& objectCopy){
n = objectCopy.n; // copy constructor
}
};
class B
{
A * a;
public:
B(A & x)
{
a = &x; // Here is the problem so I implemented a new
command
}
void print ()
{
a->print();
}
B(const B& copy){ // Class B copy constructor
a = copy.a;

the line above does not make a copy of the object.
}
const B &operator=(cons t B x){
a = x.a; // Operator
}
B::~B(){
delete a;

if you delete - make sure you have a correspoinding new.


}
};
int main()
{
A a(5);
A a1(7);
a1.print();
B b(a1);
b.print();
B c(a);
b.print();
b = c;
b.print();
cout << endl;
int trick;
cin >trick;
return 0;
}
//--------------------End of Orignal Copy-----------------------
----Version altered with new command in class B--------
#include <iostream>
using namespace std;
class A
{

... see earlier commens
};
class B
{
A * a;
public:
B(A & x)

B( const A & x )
{
a = new A(x); //New command

better
}
void print ()
{
a->print();
}
B(const B& copy){ // Class B copy constructor
a = copy.a;

// try this one
B(const B& copy) a( new A(* copy.a) ){}
}
const B &operator=(cons t B x){
a = x.a; // Operator

delete a;
a = new A(* copy.a);


}
B::~B(){
delete a;
}
};
int main()
{
A a(5);
A a1(7);
a1.print();
B b(a1);
b.print();
B c(a);
b.print();
b = c;
b.print();
cout << endl;
int trick;
cin >trick;
return 0;
}
//---------------------------------------------------------------------
Works fine but say if i change main() so it looks like this
------------------ Aletered main -----------------
int main()
{
A a(5);
B b = a;
{
A a1 (7);
B b1 =a1;
b = b1;
}
b.print();
cout << endl;
int trick;
cin >trick;
return 0;
}
--------------------- End of altered main--------------------
I get a bunch of junk so I found out i need to make a deep copy of B.

That's expected....
...
any help would be appreciated.

Hope it helps...- Hide quoted text -

- Show quoted text -- Hide quoted text -

- Show quoted text -- Hide quoted text -

- Show quoted text -- Hide quoted text -

- Show quoted text -
hey Gianni,

This code was given to me as trying to understand classes better. I
looked in the book and tried to make a new pointer to *a but falied
several times before I posted this message.

Mar 30 '07 #6
Mike Wahler wrote:
"Mark P" <us****@fall200 5REMOVE.fastmai lCAPS.fmwrote in message
news:jt******** *********@newss vr23.news.prodi gy.net...
>Gianni Mariani wrote:
>>the code in the OP has a number of inconsistantcie s.

---------------- Original Copy-----------------------
#include <iostream>
using namespace std;

class A
{
int n ;
public:
A():n(0)
The line above is valid - this is better:

A():n()

{
}
Why is that better? Granted they do the same thing, but the 0 seems more
transparent.

If the type of 'n' is later changed to some other
type where 0 is not a valid initializer, the syntax
n() will still cause 'n' to be default constructed,
and in the case of scalar types, still initialized to zero.
True-- and yours is the answer I was anticipating-- but if you're
modifying something as important as the data type of a member, a warning
from the compiler to recheck your constructor doesn't seem like such a
bad thing.
Mar 30 '07 #7
Mark P wrote:
....
True-- and yours is the answer I was anticipating-- but if you're
modifying something as important as the data type of a member, a warning
from the compiler to recheck your constructor doesn't seem like such a
bad thing.
There are only so many ways that you can default construct a scalar.
Mar 30 '07 #8
john wrote:
.....
>
---------------------------------------
I changes the code to the following, and their is a parse error?

in the line
B(const B& copy) a( new A(* copy.a) )

B and a are both making a copy??
OK - this should give you a better idea - when playing/learning about
C++ objects it's usually good to output a message at the constructor and
destructor just to get a good idea of what happens when.

I compiled this below so it should compile on your system as well

#include <string>
#include <iostream>
using namespace std;

const bool doecho = true;

template <typename T>
void Echo( T * obj, const std::string & str )
{
if ( doecho )
{
cerr << "Echo (" << obj << ") - " << str << "\n";
}
}

class A
{
int n;

public:

A()
: n()
{
Echo( this, "Default construct A" );
}

A( int x )
: n(x)
{
Echo( this, "Construct A(int)" );
}

// A( const A& ) ... normally use default copy constructor
A( const A & ia )
: n( ia.n )
{
Echo( this, "Construct A( const A& )" );
}

~A()
{
Echo( this, "~A()" );
}

void print()
{
cout << n << "\n\n";
}

};

class B
{

A * a;

public:

// all constructors should new an A

B(const A & x)
: a( new A(x) ) // initialize with an A - make a new A here
{
Echo( this, "Construct B(const A&)" );
}

B(const B & copy)
: a( new A(* copy.a) ) // deep copy the A
{
Echo( this, "Construct B(const B&)" );
}

B & operator=(const B & x)
{
Echo( this, "B::operato r =(const B&) - start" );

// need to make a new A from the B coming in
// and we need to delete the A that is currently
// being pointed to
// make this thread safe
// new can throw so make it so things can recover
A * pa( a );

// the "new" A pointer replaces the old A pointer
a = new A( * x.a );

// we didn't throw - delete the old A object
delete pa;

Echo( this, "B::operato r =(const B&) - end" );

// assignment should always return one-self
return *this;
}

// the destructor should delete the A new()ed in the
// constructor or the assignment operator
~B()
{
Echo( this, "~B() - start" );
delete a;
Echo( this, "~B() - end" );
}

void print ()
{
a->print();
}

};

//---------------------------------------------------------------------------
int main()
{

A a(5);

B b = a;

{

A a1(7);
B b1 = a1;
b = b1;
}

b.print();
cout << endl;
int trick;
cin >trick;

return 0;
}
Mar 30 '07 #9

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

Similar topics

7
4551
by: Nicolay Korslund | last post by:
Hi! I'm having a little trouble with the typecast operator, can anybody help me with the rules for when the this operator is invoked? In the class 'Test' in the code below, the typecast operator returns a 'mytype'. In main() I use the operator on 'Test'-class objects. If 'mytype' is a pointer the operator works fine. But if I instead try to call an overloaded operator, the typecast operator is not invoked, and I get a compiler error...
3
8094
by: KK | last post by:
Hi, im working on this bigInt class. Need help writing algorithm for the operator*, andy help will be appreciated. Thanks in advance bigInt.h =================================================================================== //class bigInt implements big integers by storing the digits of a big //integer in a private vector data member called digit. Since it uses a //vector the size of the big integer can be indefinitely large. This...
5
3809
by: Jason | last post by:
Hello. I am trying to learn how operator overloading works so I wrote a simple class to help me practice. I understand the basic opertoar overload like + - / *, but when I try to overload more complex operator, I get stuck. Here's a brief description what I want to do. I want to simulate a matrix (2D array) from a 1D array. so what I have so far is something like this: class Matrix
13
4653
by: jstanforth | last post by:
This is probably a very obvious question, but I'm not clear on what operators need to be implemented for std::map.find() to work. For example, I have a class MyString that wraps std::string, and which also implements ==, <, <=, >, >=, etc. (Those operators are tested and working correctly.) If I assign map = "world", it saves the MyString's correctly in the map. But a subsequent call to map.find("hello") returns map.end(). Even more...
4
6749
by: Rock | last post by:
I'm in the process of writing this program for complex numbers and I use DevC++. My professor on the other hand compiles on Borland 5.5. So I ocasionally save and run my work on Borland to see if it caught anything, it's very picky... Anyway, the code below works on Dev, and it compiles fine on Borland, but when I run it from borland, there is no output, no error, it just skips right over the freind ostream call. HELP! I'm new to this...
6
1941
by: idikoko | last post by:
I need help overloafing the <,> operators! I wrote a very simple complex numbers class which basically treats a double as an imaginary number. I wrote the code to overload the >,< operators but they don't seem to compile. I'm stuck as to what to do next, please help class Complex { public: Complex( double = 0.0); // constructor Complex operator+( const Complex & ) const; // addition
6
3555
by: Bill foust | last post by:
I'm running into a situation there I think an operator overload would solve the issue, but I'm unable to make it work for some reason. If anyone can help here I would appreciate it. I have a base class that is common to many other classes. public class Base .... end class I have 2 seperate classes that inherit from base
11
1981
by: Zilla | last post by:
I have the following simple program. I just want to be able to do math operations (+, -, =)on Timer sublcasses, but want to handle cases where either rhs or lhs is an intrinsic value, However, the compile fails in my g++ 2.95 compiler during the 2nd to last line of the main() with template.cpp: In function `int main()': template.cpp:24: `operator +<int>(int, const int &)' must have an argument of class or enumerated type template.cpp:...
6
2941
by: edd | last post by:
Hello all, Is there a way to determine whether a particular type supports the -> operator at compile time? I'm trying to write a template function (or a series of overloads) that will yield the raw pointer at "the end of the arrow". For types that support the operator, I have a reasonable solution, but I'd like to have a null pointer returned if the operator isn't supported by a particular object.
17
1629
by: Corey Cooper | last post by:
I have a class for which I needed to create an operator= function. I then use that as a base class for another class, which also needs an operator=. What is the syntax to use in the derived class operator= function to copy the base classes variables in the derived class (without just copying the code?) A much simplified example: class Base {
0
9790
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9642
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10770
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10481
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
6948
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5616
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4409
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 we have to send another system
2
3956
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3074
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.