473,394 Members | 1,740 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Copy Inherited Objects

I'm attempting to learn how to use inheritance in C++, the following
program should print the word 'Orange' on the screen but it prints
'Apple' instead. Can someone explain what is wrong?

#include <iostream>

class Fruit
{
public:
virtual const char* get_name() {return "(nothing)";}
};

class Apple: public Fruit
{
public:
const char* get_name() {return "Apple";}
};

class Orange: public Fruit
{
const char* get_name() {return "Orange";}
};

int main()
{
std::cout << "Test inheritation" << std::endl;

Fruit *myfruit1 = new Apple();
Fruit *myfruit2 = new Orange();
Fruit *myfruit3 = new Apple();

std::cout << "myfruit1 = " << myfruit1->get_name() <<
std::endl; // Prints "Apple"
std::cout << "myfruit2 = " << myfruit2->get_name() <<
std::endl; // Prints "Orange"
std::cout << "myfruit3 = " << myfruit3->get_name() <<
std::endl; // Prints "Apple"

// The following does not work
std::cout << "Now change myfruit3 from Apple to Orange..." <<
std::endl;
*myfruit3 = *myfruit2;

// Prints "Apple" but should print "Orange"
std::cout << "myfruit3 = " << myfruit3->get_name() << std::endl;

// Wait for a keypress
std::cin.get();

delete myfruit1;
delete myfruit2;
delete myfruit3;
}
Jun 27 '08 #1
5 1188
timid wrote:
#include <iostream>

class Fruit
{
public:
virtual const char* get_name() {return "(nothing)";}
Use std::string rather than char*.

Also, a function such as "get_name" should usually be declared const.
};

class Apple: public Fruit
{
public:
const char* get_name() {return "Apple";}
};

class Orange: public Fruit
{
const char* get_name() {return "Orange";}
};

int main()
{
std::cout << "Test inheritation" << std::endl;

Fruit *myfruit1 = new Apple();
Fruit *myfruit2 = new Orange();
Fruit *myfruit3 = new Apple();

[...]

// The following does not work
std::cout << "Now change myfruit3 from Apple to Orange..." <<
std::endl;
*myfruit3 = *myfruit2;
* derefences the pointer, yielding the object it's pointing to.
Consequently, in your example you don't assign the _pointers_, you
assign the _objects_ they are pointing to. That's a huge difference.
Assigning an Orange to an Apple obviously does not do anything because
you did not specify anything to happen in case of such an assignment.
The invisible assignment operator automatically generated by the
compiler is empty. In other words, the Apple is completely unaffected by
the operation.
If you want to assign a pointer to another pointer, you have to write:

myfruit3 = myfruit2;

However, in your program this would have disastrous results because you
would lose the old value of myfruit3, which means you cannot delete your
second Apple anymore. (You'd have to save the old value somewhere, for
example in a temporary pointer variable.)

What do you try to achieve by having myfruit3 point to a different object?
--
Christian Hackl
Jun 27 '08 #2
On May 17, 10:49 pm, Christian Hackl <ha...@sbox.tugraz.atwrote:
timid wrote:
#include <iostream>
class Fruit
{
public:
virtual const char* get_name() {return "(nothing)";}

Use std::string rather than char*.

Also, a function such as "get_name" should usually be declared const.
};
class Apple: public Fruit
{
public:
const char* get_name() {return "Apple";}
};
class Orange: public Fruit
{
const char* get_name() {return "Orange";}
};
int main()
{
std::cout << "Test inheritation" << std::endl;
Fruit *myfruit1 = new Apple();
Fruit *myfruit2 = new Orange();
Fruit *myfruit3 = new Apple();
[...]
// The following does not work
std::cout << "Now change myfruit3 from Apple to Orange..." <<
std::endl;
*myfruit3 = *myfruit2;

* derefences the pointer, yielding the object it's pointing to.
Consequently, in your example you don't assign the _pointers_, you
assign the _objects_ they are pointing to. That's a huge difference.
Assigning an Orange to an Apple obviously does not do anything because
you did not specify anything to happen in case of such an assignment.
The invisible assignment operator automatically generated by the
compiler is empty. In other words, the Apple is completely unaffected by
the operation.

If you want to assign a pointer to another pointer, you have to write:

myfruit3 = myfruit2;

However, in your program this would have disastrous results because you
would lose the old value of myfruit3, which means you cannot delete your
second Apple anymore. (You'd have to save the old value somewhere, for
example in a temporary pointer variable.)

What do you try to achieve by having myfruit3 point to a different object?

--
Christian Hackl
Thank's for the help so far, it would appear that I need to learn a
lot more.

I'm going to try & rewrite this program so it'll work.
Jun 27 '08 #3
Hi!

Christian Hackl schrieb:
>class Fruit
{
public:
virtual const char* get_name() {return "(nothing)";}

Use std::string rather than char*.
Normally I would agree, but in case of /const/ char* there is usually no
problem. Only the use of char* for strings in C++ applications is nearly
always a risk. On the other hand, using std::string for this (and
similar) purposes is a significant runtime overhead. Only if you already
have a std::string it is more advisable to return std::string, or if
this causes no threading or aliasing problem const std::string&.
Also, a function such as "get_name" should usually be declared const.
That's obviously true.

If you want to assign a pointer to another pointer, you have to write:

myfruit3 = myfruit2;

However, in your program this would have disastrous results because you
would lose the old value of myfruit3, which means you cannot delete your
second Apple anymore. (You'd have to save the old value somewhere, for
example in a temporary pointer variable.)

What do you try to achieve by having myfruit3 point to a different object?
I think the OP is seeking for something like a clone method.
Marcel
Jun 27 '08 #4
On 17 mai, 23:11, timid <visicalcena...@googlemail.comwrote:
I'm attempting to learn how to use inheritance in C++, the
following program should print the word 'Orange' on the screen
but it prints 'Apple' instead. Can someone explain what is
wrong?
#include <iostream>
class Fruit
{
public:
virtual const char* get_name() {return "(nothing)";}
};
class Apple: public Fruit
{
public:
const char* get_name() {return "Apple";}
};
class Orange: public Fruit
{
const char* get_name() {return "Orange";}
};
int main()
{
std::cout << "Test inheritation" << std::endl;
Fruit *myfruit1 = new Apple();
Fruit *myfruit2 = new Orange();
Fruit *myfruit3 = new Apple();
std::cout << "myfruit1 = " << myfruit1->get_name() <<
std::endl; // Prints "Apple"
std::cout << "myfruit2 = " << myfruit2->get_name() <<
std::endl; // Prints "Orange"
std::cout << "myfruit3 = " << myfruit3->get_name() <<
std::endl; // Prints "Apple"
// The following does not work
std::cout << "Now change myfruit3 from Apple to Orange..." <<
std::endl;
*myfruit3 = *myfruit2;
And what do you expect this to do? You cannot change the type
of an existing object. In general, when inheritence is
involved, you don't support assignment and copy.
// Prints "Apple" but should print "Orange"
std::cout << "myfruit3 = " << myfruit3->get_name() << std::endl;
No. Should print "Apple". But a lot of typical implementations
of the assignment operator (for more complicated types) will
result in undefined behavior. The base class for an inheritence
hierarchy should normally forbid assignment, so that the
situation can't arrive, even accidentally.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #5
On 18 mai, 11:29, Marcel Müller <news.5.ma...@spamgourmet.comwrote:
I think the OP is seeking for something like a clone method.
Or the letter/envelope idiom. Or perhaps just simply some
information on OO design; he hasn't really expressed a concrete
need for assignment.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #6

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...
1
by: Russ Ford | last post by:
Hi all, I'm trying to get inheritance and constructors clear in my head (and in my code). I have the following inheritance situation (all derivations public): A is the base class B is...
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...
2
by: Josh Mcfarlane | last post by:
I'm doing recomposition of objects from binary streams, and the best way for me to write them out is to write base class data first, forward to inherited classes, pointer class values, etc. Now,...
6
by: Andreas | last post by:
Hello list, what about uniqueness of inherited primary keys ? eg you have : create table objects ( id int4, date_created timestamp(0), primary key (id)
35
by: MuZZy | last post by:
Hi All, I got a issue here and hope someone can help me: Let's consider this code: // =================== CODE START ================================= using System; using System.Data; ...
0
by: brian.mills | last post by:
I have a web service in a technology called Jade. It is returning a StudentObject, which has an array of Application Objects on it. The Application objects never are actually Application Instances,...
0
by: porter_wss | last post by:
I am a bit confused on serializing objects and inherited objects. What I am trying to accomplish is creating a base object and an inherited object with additional properties. The sender of these...
15
by: Brett Wickard | last post by:
Ok, this should be simple, but how do I copy a reference type by value? Meaning SomeComplexObject s1 = new SomeComplexObject (); SomeComplexObject s2 = new SomeComplexObject (); s1.color =...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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
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...

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.