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
13 2021
"Jack" <ja**@ss.comwro te in message news:j6******** *************** *********@4ax.c om...
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.
Rather, it would be a flaw in the language if it supported that, given the cost in space and/or
execution time needed and the very limited use it would get. For one thing, at run-time the program
would have to check the type stored to know how many bytes to advance to reach the array element
addressed - a complete waste when the objects are of the declared type.
You can always use an array of Base*, where each Base * may point to a Base or a Derived object, and
each would behave polymorphically .
DW
On Fri, 06 Oct 2006 18:45:34 +1300, Ian Collins <ia******@hotma il.com>
wrote:
>Jack wrote:
>On Thu, 5 Oct 2006 23:49:41 -0400, "Victor Bazarov" <v.********@co mAcast.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.
Very good explanation! It makes perfect sense now. An array of
pointers, of course! Thank you!
On Fri, 06 Oct 2006 00:04:30 -0400, Nate Barney <na********@gma il.com>
wrote:
>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
Sure, why not. LOL!
class Base
{
protected:
const int m_base;
public:
Base() : m_base( 1 ){}
const int GetBaseMember() { return m_base; }
};
Jack wrote:
On Fri, 06 Oct 2006 00:04:30 -0400, Nate Barney <na********@gma il.com>
wrote:
>Jack wrote:
>>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.
Sure, why not. LOL!
class Base
{
protected:
const int m_base;
public:
Base() : m_base( 1 ){}
const int GetBaseMember() { return m_base; }
};
Actually, I meant:
int GetBaseMember() const { return m_base; } This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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...
|
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
|
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
|
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).
|
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?
| |
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...
|
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...
|
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()
|
by: Fokko Beekhof |
last post by:
Hello all,
please consider the following code:
--------------------------------------------------
#include <tr1/memory>
struct BaseA
{
int x;
|
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...
|
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,...
| |
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...
|
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,...
|
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...
|
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();...
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |