473,796 Members | 2,570 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array of classes as a function parameter...pol ymorphism question.

I have a class called "Base". This class has a protected member
variable "m_base" which can be retrieved using the public member
function "GetBaseMember" . "m_base" is initialized to "1" and is never
changed.

I have another class which is a subclass of the "Base" class called
"Derived". This derived class has a member variable called
"m_derived" . "m_derived" is initialized to "2" and is never changed.

I pass an array of "Base" classes as a parameter to a function.The
individual items in this array may or may not be subclasses of the
"Base" class. Within this function, the member function
"GetBaseMem ber" is called, and the value of "m_base" is displayed to
the screen.

Intuitively, the output should always be "1", but unfortunately it's
not. The output alternates between "1" and "2". I don't understand why
this is. How else can I pass this "subclassab le" class array to a
function and retrieve the expected base class member variable? What
concept am I missing here?

#include <iostream>
using namespace std;

class Base
{
protected:
int m_base;

public:
Base() : m_base( 1 ){}
int GetBaseMember() { return m_base; }
};

class Derived : public Base
{
protected:
int m_derived;

public:
Derived() : Base(), m_derived( 2 ){}
};

void Foo( int cItems, Base b[] )
{
int i = 0;
for ( i = 0; i < cItems; i++ )
{
// I want the output to always be 1,
// but it alternates between 1 and 2
cout << "m_base = " << b[i].GetBaseMember( ) << endl;
}
}

int main()
{
const int NUM_ITEMS = 4;
Derived d[NUM_ITEMS];

Foo( NUM_ITEMS, d );

return 0;
}
Oct 6 '06 #1
13 2020
Jack wrote:
I have a class called "Base". This class has a protected member
variable "m_base" which can be retrieved using the public member
function "GetBaseMember" . "m_base" is initialized to "1" and is never
changed.

I have another class which is a subclass of the "Base" class called
"Derived". This derived class has a member variable called
"m_derived" . "m_derived" is initialized to "2" and is never changed.

I pass an array of "Base" classes as a parameter to a function.
Actually, you don't. Your function *expects* an array of Base objects.
You *pass* it an array of *Derived*s.
The
individual items in this array may or may not be subclasses of the
"Base" class.
If it's an array of 'Base', items in it are *always* objects of 'Base'.
None of them can be subobjects of anything. They are all stand-alone
objects, essentially.
Within this function, the member function
"GetBaseMem ber" is called, and the value of "m_base" is displayed to
the screen.

Intuitively, the output should always be "1", but unfortunately it's
not.
The behaviour of your program is undefined. You pass an array of
Derived objects where an array of Base is expected. There is no
conversion between the two. And since you declare your function as
receiving a *pointer* to 'Base', the compiler does not complain.
The undefined behaviour occurs when you index that pointer with any
expression other than 0.
The output alternates between "1" and "2". I don't understand why
this is.
The reason is immaterial. The behaviour is undefined; anything may
happen.
How else can I pass this "subclassab le" class array to a
function and retrieve the expected base class member variable? What
concept am I missing here?
You want to use polymorphism. Probably compile-time one, through
templates. Your 'Foo' function should be defined as

template<class BDvoid Foo(int cItems, BD b[])
{
// keep inside just like you have it.
}
>
#include <iostream>
using namespace std;

class Base
{
protected:
int m_base;

public:
Base() : m_base( 1 ){}
int GetBaseMember() { return m_base; }
};

class Derived : public Base
{
protected:
int m_derived;

public:
Derived() : Base(), m_derived( 2 ){}
};

void Foo( int cItems, Base b[] )
{
int i = 0;
for ( i = 0; i < cItems; i++ )
{
// I want the output to always be 1,
// but it alternates between 1 and 2
cout << "m_base = " << b[i].GetBaseMember( ) << endl;
}
}

int main()
{
const int NUM_ITEMS = 4;
Derived d[NUM_ITEMS];

Foo( NUM_ITEMS, d );

return 0;
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 6 '06 #2
Victor Bazarov wrote:
Jack wrote:
>How else can I pass this "subclassab le" class array to a
function and retrieve the expected base class member variable? What
concept am I missing here?

You want to use polymorphism. Probably compile-time one, through
templates. Your 'Foo' function should be defined as

template<class BDvoid Foo(int cItems, BD b[])
{
// keep inside just like you have it.
}
Even better would be:

template <typename It>
void Foo(It begin,It end)
{
for (It i = begin; i != end; ++i)
cout << "m_base = " << i->GetBaseMember( ) << endl;
}

int main()
{
const int NUM_ITEMS = 4;
Derived d[NUM_ITEMS];

Foo(d,d + NUM_ITEMS);

return 0;
}

This allows the use of STL containers in addition to arrays, or
subranges of either.
Oct 6 '06 #3
Jack wrote:
I have a class called "Base". This class has a protected member
variable "m_base" which can be retrieved using the public member
function "GetBaseMember" . "m_base" is initialized to "1" and is never
changed.
[snip]
class Base
{
protected:
int m_base;

public:
Base() : m_base( 1 ){}
int GetBaseMember() { return m_base; }
};
I know this is just an example, but if m_base never changes, why not
declare it const? Same goes for GetBaseMember.

Nate
Oct 6 '06 #4
Nate Barney wrote:
Victor Bazarov wrote:
>Jack wrote:
>>How else can I pass this "subclassab le" class array to a
function and retrieve the expected base class member variable? What
concept am I missing here?

You want to use polymorphism. Probably compile-time one, through
templates. Your 'Foo' function should be defined as

template<cla ss BDvoid Foo(int cItems, BD b[])
{
// keep inside just like you have it.
}

Even better would be:

template <typename It>
void Foo(It begin,It end)
{
for (It i = begin; i != end; ++i)
Generally speaking all you need is

while (begin != end)
cout << "m_base = " << i->GetBaseMember( ) << endl;
cout << "m_base = " << (*begin++).GetB aseMember() << endl;
}

int main()
{
const int NUM_ITEMS = 4;
Derived d[NUM_ITEMS];

Foo(d,d + NUM_ITEMS);

return 0;
}

This allows the use of STL containers in addition to arrays, or
subranges of either.
I agree, it's better. But a concept of an iterator is not something
a beginner would grasp easily, I'm afraid, especially if they are
taught about arrays.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 6 '06 #5
Victor Bazarov wrote:
Nate Barney wrote:
>template <typename It>
void Foo(It begin,It end)
{
for (It i = begin; i != end; ++i)

Generally speaking all you need is

while (begin != end)
> cout << "m_base = " << i->GetBaseMember( ) << endl;

cout << "m_base = " << (*begin++).GetB aseMember() << endl;
>}
That's cool. I never thought of that. I guess I'm used to writing such
functions this way:

template <typename It>
void Foo(const It &begin,const It &end)
{
}

in case the iterator is larger than a pointer, in which case the extra
counter variable would be required. Standard library iterators are
probably not, but custom iterators may well be.
I agree, it's better. But a concept of an iterator is not something
a beginner would grasp easily, I'm afraid, especially if they are
taught about arrays.
Makes sense. I just thought I'd provide this example in case the OP
could grasp the concept and had just not been exposed to it.

Nate
Oct 6 '06 #6
Nate Barney wrote:
Victor Bazarov wrote:
>Nate Barney wrote:
>>template <typename It>
void Foo(It begin,It end)
{
for (It i = begin; i != end; ++i)

Generally speaking all you need is

while (begin != end)
>> cout << "m_base = " << i->GetBaseMember( ) << endl;

cout << "m_base = " << (*begin++).GetB aseMember() << endl;
>>}

That's cool. I never thought of that. I guess I'm used to writing such
functions this way:

template <typename It>
void Foo(const It &begin,const It &end)
{
}

in case the iterator is larger than a pointer, in which case the extra
counter variable would be required. Standard library iterators are
probably not, but custom iterators may well be.
[snip]

Note that the standard algorithms take iterators by value. The STL is very
much designed under the assumption that copying iterators is cheap. It
would be unwise to design iterators the break this assumption. I usually
follow the precedent set by the standard library. Thus, when taking
iterators as arguments, I take them by value. In my opinion, making
iterators reasonably small is part of good iterator design.

Also, there is not really a need for big iterators: in tree based data
structures one can use back pointers so that iterators can just be node
pointers. When all else fail, one can implement the iterator as a little
wrapper around a shared_ptr (been there, done that: the tree structure
underlying a rope does not allow for back pointers). I have yet to learn of
a situation, where an iterator has to be big.
Best

Kai-Uwe Bux
Oct 6 '06 #7
On Thu, 5 Oct 2006 23:49:41 -0400, "Victor Bazarov"
<v.********@com Acast.netwrote:
>The behaviour of your program is undefined. You pass an array of
Derived objects where an array of Base is expected. There is no
conversion between the two.
I was under the assumption that C++ would support polymorphism for
arrays of subclassed objects, but I guess I was wrong. IMHO, my
algorithm being described as "undefined" is a flaw in the language. No
conversion? Isn't it obvious? I guess not for the compiler.
>You want to use polymorphism. Probably compile-time one, through
templates. Your 'Foo' function should be defined as

template<cla ss BDvoid Foo(int cItems, BD b[])
{
// keep inside just like you have it.
}
Of course I want to use polymorphism! Is there another option besides
templates though? It just seems like overkill for an extremely simple
task. The following example works fine. Why does C++ use polymorphism
for this example and not for my original one?

void Foo( Base& b )
{
// This always gives the desired output.
cout << "m_base = " << b.GetBaseMember () << endl;
}

int main()
{
const int NUM_ITEMS = 4;
Derived d[NUM_ITEMS];
int i;

for ( i = 0; i < NUM_ITEMS; i++ )
{
Foo( d[i] );
}

return 0;
}
Oct 6 '06 #8
Jack wrote:
On Thu, 5 Oct 2006 23:49:41 -0400, "Victor Bazarov"
<v.********@com Acast.netwrote:

>>The behaviour of your program is undefined. You pass an array of
Derived objects where an array of Base is expected. There is no
conversion between the two.


I was under the assumption that C++ would support polymorphism for
arrays of subclassed objects, but I guess I was wrong. IMHO, my
algorithm being described as "undefined" is a flaw in the language. No
conversion? Isn't it obvious? I guess not for the compiler.
No it isn't.

If you define and array of some base class of size N and attempt to
store derived objects of size N+M in said array, what would you expect
happen?

Use an array of pointers to base.

--
Ian Collins.
Oct 6 '06 #9
Kai-Uwe Bux wrote:
Nate Barney wrote:
>template <typename It>
void Foo(const It &begin,const It &end)
{
}

in case the iterator is larger than a pointer, in which case the extra
counter variable would be required. Standard library iterators are
probably not, but custom iterators may well be.
[snip]

Note that the standard algorithms take iterators by value. The STL is very
much designed under the assumption that copying iterators is cheap. It
would be unwise to design iterators the break this assumption. I usually
follow the precedent set by the standard library. Thus, when taking
iterators as arguments, I take them by value. In my opinion, making
iterators reasonably small is part of good iterator design.
Point well taken. Thanks for that.

Nate
Oct 6 '06 #10

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

Similar topics

9
4813
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in place of an array of base class object. Since I am using vector class(STL), the compiler does not allow me to do this. I do realize there is a pitfall in this approach(size of arrays not matching etc), but I wonder how to get around this problem. I have a class hierachy with abstract base...
24
2572
by: Alf P. Steinbach | last post by:
The eighth chapter (chapter 2.1) of my attempted Correct C++ tutorial is now available, although for now only in Word format -- comments welcome! Use the free & system-independent Open Office if you don't have Word. Classes <url: http://home.no.net/dubjai/win32cpptut/w32cpptut_02_01.zip> Introduces the C++ language feature used to define new types, namely classes. The focus in on creating safe and reusable classes. As a main
4
9700
by: mflll | last post by:
I am looking into the different techniques of handling arrays of edit boxes in Java Script. The first program below works fine. However, are there better ways of doing this, where the person writing the JavaScript doesn't have to pass the index in the "onChange" event name. I thought that one might be able to use "this.value" or compare this as
7
3202
by: Jim Carlock | last post by:
Looking for suggestions on how to handle bad words that might get passed in through $_GET variables. My first thoughts included using str_replace() to strip out such content, but then one ends up looking for characters that wrap around the stripped characters and it ends up as a recursive ordeal that fails to identify a poorly constructed $_GET variable (when someone hand-types the item into the line and makes a simple typing error).
7
6444
by: heddy | last post by:
I have an array of objects. When I use Array.Resize<T>(ref Object,int Newsize); and the newsize is smaller then what the array was previously, are the resources allocated to the objects that are now thown out of the array released properly by the CLI?
173
5736
by: Zytan | last post by:
I've read the docs on this, but one thing was left unclear. It seems as though a Module does not have to be fully qualified. Is this the case? I have source that apparently shows this. Are modules left-over from VB6, and not much used anymore? It seems that it is better to require Imports or use fully qualified names for functions in other classes/modules, but a Module doesn't require this, cluttering the global namespace. It seems...
2
2413
by: cmonthenet | last post by:
Hello, I searched for an answer to my question and found similar posts, but none that quite addressed the issue I am trying to resolve. Essentially, it seems like I need something like a virtual static function (which I know is illegal), but, is there a way to provide something similar? The class that is the target of my inquiry is a template class that interfaces to one of several derived classes through a pointer to a base class. The...
26
4887
by: aruna.mysore | last post by:
Hi all, I have a specific problem passing a function pointer array as a parameter to a function. I am trying to use a function which takes a function pointer array as an argument. I am too sure about the syntax of calling the same. #include <stdio.h> void fp1()
5
3204
by: Fokko Beekhof | last post by:
Hello all, please consider the following code: -------------------------------------------------- #include <tr1/memory> struct BaseA { int x;
0
9684
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
9530
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
10236
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...
1
10182
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10017
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9055
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7552
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6793
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();...
1
4120
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

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.