472,989 Members | 3,117 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Array of object from varius subclasses

Hi all,

I have a base class and some subclasses; I need to define an array of
objects from these various subclasses. What I have is something like:

{

//I have a base class, something like:

class CPeople {
public:
virtual void Input() {printf("Inside CPeople::Input()\n");}
virtual void Show() {printf("Inside CPeople::Show()\n");}
};

//and some subclasses

class CMale : public CPeople {
public:
void Input() {};
void Show() {};
};

class CFemale : public CPeople {
public:
void Input() {printf("Inside CFemale::Input()\n");}
void Show() {printf("Inside CFemale::Show()\n");}
};

//Now I need an array of people...

CPeople MyArray[10];

//I create a CFemale Object...

CFemale temp;
temp.Input();

//I assign this object to an array element:

MyArray[1] = temp;
MyArray[1].Show();

return 0;
}
// I get :
// "Inside CFemale::Input()"
// "Inside CPeople::Show()"

So when I call MyArray[1].Show() the function called is the one
defined in the base class ( CPeople::Show() ).

What do I need to do to get the desired behaviour?

Thank you in advance...
Marco
Jul 22 '05 #1
8 2954
Marco wrote:

What do I need to do to get the desired behaviour?


You defined an array of CPeople objects. No matter what objects you assign
to them, they won't ever turn into anything else.

You only get polymorphic behaviour (which is what you supposedly meant by
"desired"), when you invoke an object's virtual member function
through a pointer or a reference to a base class.

For example:

CPeople* MyArray[10];

MyArray[1] = new CFemale;
MyArray[1]->Show();

Max
Jul 22 '05 #2
Hi Max,

Ok, I got it... Thank you!

Marco

"Max M." <ed***@maxim.comm2000.it> ha scritto nel messaggio
news:br**********@newsreader.mailgate.org...
Marco wrote:

What do I need to do to get the desired behaviour?


You defined an array of CPeople objects. No matter what objects you assign
to them, they won't ever turn into anything else.

You only get polymorphic behaviour (which is what you supposedly meant by
"desired"), when you invoke an object's virtual member function
through a pointer or a reference to a base class.

For example:

CPeople* MyArray[10];

MyArray[1] = new CFemale;
MyArray[1]->Show();

Max

Jul 22 '05 #3

"Marco" <hw***********@tin.it> wrote in message
news:hC******************@tornado.fastwebnet.it...
Hi Max,

Ok, I got it... Thank you!

Marco

"Max M." <ed***@maxim.comm2000.it> ha scritto nel messaggio
news:br**********@newsreader.mailgate.org...
Marco wrote:

What do I need to do to get the desired behaviour?


You defined an array of CPeople objects. No matter what objects you assign to them, they won't ever turn into anything else.

You only get polymorphic behaviour (which is what you supposedly meant by "desired"), when you invoke an object's virtual member function
through a pointer or a reference to a base class.

For example:

CPeople* MyArray[10];

MyArray[1] = new CFemale;
MyArray[1]->Show();

Max



Note that Max made the change from an array of CPeople to an array of
CPeople*. Without this change, inserting an object of a subclasss with a
larger size would corrupt your memory.

Tom
Jul 22 '05 #4
Thomas Wintschel wrote:
Note that Max made the change from an array of CPeople to an array of
CPeople*.**Without*this*change,*inserting*an*objec t*of*a*subclasss*with*a
larger size would corrupt your memory.


Tom, this sentence doesn't make much sense. One cannot *insert* an object
into an array. Rather, one can use the assignment operator to change an
element's value. Marco's original code was perfectly legal and had well
defined behaviour, though different from what he expected.

Max
Jul 22 '05 #5
"Max M." <ed***@maxim.comm2000.it> wrote in message
news:br**********@newsreader.mailgate.org...
Thomas Wintschel wrote:
Note that Max made the change from an array of CPeople to an array of
CPeople*. Without this change, inserting an object of a subclasss with a
larger size would corrupt your memory.


Tom, this sentence doesn't make much sense. One cannot *insert* an object
into an array. Rather, one can use the assignment operator to change an
element's value. Marco's original code was perfectly legal and had well
defined behaviour, though different from what he expected.

Max


Apologies. I should not have used the word 'insert' and duly chastise
myself.

I was hoping to help him avoid running into any unexpected behaviour by
pointing out that instances of subclasses with additional data members could
not safely be stored in an array of base class objects, as in the following
example.

class Small
{
public:
Small() : m_n1(1) {};
Small& operator = (const Small &rhs)
{
m_n1 = rhs.m_n1;
return *this;
}
int Getn1() { return m_n1; }
void Setn1(int n) { m_n1 = n; }
private:
int m_n1;
};

// Make 'Big' twice the size of a 'Small'
class Big : public Small
{
public:
Big() : m_n2(2) {};
Big& operator = (const Big &rhs)
{
Small::operator=(rhs);
m_n2 = rhs.m_n2;
return *this;
}
int Getn2() { return m_n2; }
void Setn2(int n) { m_n2 = n; }
private:
int m_n2;
};

int main()
{
Small smalls[2];

Big big;
smalls[0] = big; // Only the 'Small' part of big is copied

// Unsafe, smalls[0] contains a 'Small', not a 'Big'
Big* pBig = static_cast< Big* >(&smalls[0]);

// Returns 1, as expected
int n1 = pBig->Getn1();

// Also returns 1, since it reading the value from
// the location where smalls[1] is stored
int n2 = pBig->Getn2();

// Modifying the subclass now affects the subsequent element in the
array
pBig->Setn2(3);
// Which now contains the value 3 instead of 1
n1 = smalls[1].Getn1();

// Extra dangerous, since it goes past the end of the array
pBig = static_cast< Big* >(&smalls[1]);
// Returns 3 as the result of previous manipulations
n1 = pBig->Getn1();
// Returns ?
n2 = pBig->Getn2();
}
Jul 22 '05 #6
On Sun, 14 Dec 2003 02:08:56 +0100, "Max M." <ed***@maxim.comm2000.it>
wrote:
Thomas Wintschel wrote:
Note that Max made the change from an array of CPeople to an array of
CPeople*.**Without*this*change,*inserting*an*objec t*of*a*subclasss*with*a
larger size would corrupt your memory.


Tom, this sentence doesn't make much sense. One cannot *insert* an object
into an array. Rather, one can use the assignment operator to change an
element's value. Marco's original code was perfectly legal and had well
defined behaviour, though different from what he expected.


He was referring to slicing which, although it might not "corrupt"
memory here, will indeed cause memory leaks.
--
Bob Hairgrove
No**********@Home.com
Jul 22 '05 #7
Hi,

Thank you for all your replies and the information!

Marco
"Bob Hairgrove" <wouldnt_you_like@to_know.com> ha scritto nel messaggio
news:3f**************@news.webshuttle.ch...
On Sun, 14 Dec 2003 02:08:56 +0100, "Max M." <ed***@maxim.comm2000.it>
wrote:
Thomas Wintschel wrote:
Note that Max made the change from an array of CPeople to an array of
CPeople*. Without this change, inserting an object of a subclasss with a larger size would corrupt your memory.


Tom, this sentence doesn't make much sense. One cannot *insert* an object
into an array. Rather, one can use the assignment operator to change an
element's value. Marco's original code was perfectly legal and had well
defined behaviour, though different from what he expected.


He was referring to slicing which, although it might not "corrupt"
memory here, will indeed cause memory leaks.
--
Bob Hairgrove
No**********@Home.com

Jul 22 '05 #8
Bob Hairgrove wrote:

He was referring to slicing which, although it might not "corrupt"
memory here, will indeed cause memory leaks.


I don't get you. In what circumstances could slicing result in a memory
leak? Are you implying the code from Marco's first post (which assigned
derived-class objects to base-class ones) causes memory leaking? It does
not, actually.

Max
Jul 22 '05 #9

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

Similar topics

18
by: Steven Bethard | last post by:
In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that instead of...
5
by: Martin Magnusson | last post by:
Hi! I have a class with a private member which is a pointer to an abstract class, which looks something like this: class Agent { public: void Step( Base* newB ); private:
6
by: billy | last post by:
I've got a set of subclasses that each derive from a common base class. What I'd like to do is create a global array of the class types (or, class names) that a manager class can walk through in...
11
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you...
9
by: GiantCranesInDublin | last post by:
Hi, I am looking for the best performing solution for modifying and iterating an object graph in JavaScript. I have outlined below a simplified example of the object model and examples of how I...
3
by: Simon Hart | last post by:
Hi, I am trying to implement some functionality as seen in MS CRM 3.0 whereby a basic Xml is deserialized into an object which contains properties. What I want to do from here is; cast the basic...
5
by: JH | last post by:
Hi I found that a type/class are both a subclass and a instance of base type "object". It conflicts to my understanding that: 1.) a type/class object is created from class statement 2.) a...
4
by: Technics | last post by:
Ok I will be as clearer as I can (sorry for english/technical mistakes) I would like to write an audio application that supports ASIO drivers. I downloaded the ASIO sdk from Stainberg and I read...
14
by: sumsin | last post by:
From 'Inside the C++ Object Model' by 'Stanley B. Lippman' 'The primary strength of the C++ Object Model is its space and runtime efficiency. Its primary drawback is the need to recompile...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
3
SueHopson
by: SueHopson | last post by:
Hi All, I'm trying to create a single code (run off a button that calls the Private Sub) for our parts list report that will allow the user to filter by either/both PartVendor and PartType. On...

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.