Inheritance question

M

MUTOOLS

class A {

public:
char String[20];
};

class B : public A {

public:
char String[20];
};

class C : public B {

public:
char String[20];
};

void Test() {

A a,*ap;
B b;
C c;

strcpy(a.String,"Adios");
strcpy(b.String,"ByeBye");
strcpy(c.String,"Ciao");

printf("%s\n",a.String); // prints 'Adios' -> OK
printf("%s\n",b.String); // prints 'ByeBye' -> OK
printf("%s\n",c.String); // prints 'Ciao' -> OK

ap=&a;
printf("%s\n",ap->String); // prints 'Adios' -> OK
ap=&b;
printf("%s\n",ap->String); // prints 'IIIIIIIIIIIIIIIIIIIIByeBye' -> Strange! Why?
ap=&c;
printf("%s\n",ap->String); // prints 'IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIICiao' -> Strange! Why?
}

When doing

ap=&b;

Why doesn't ap->String show "Adios"? Or "ByeBye"? (that was what i wanted to test)

I searched the net but couldn't find the answer. Lot of info about deriving member functions, but not about deriving member variables.

Any answer or links are much appreciated.

Thanks.
 
T

Thomas J. Gritzan

MUTOOLS said:
class A {

public:
char String[20];
};

class A contains a char array.
class B : public A {

public:
char String[20];
};
[...all of class C snipped...]

class B contains two char arrays
void Test() {

A a,*ap;
B b;

strcpy(a.String,"Adios");

Here you initialize the char array of a.
strcpy(b.String,"ByeBye");

Here you initialize one char array of b. The char array of b's base
class is left uninitialized. Accessing it yields undefined behaviour.
printf("%s\n",a.String); // prints 'Adios' -> OK
printf("%s\n",b.String); // prints 'ByeBye' -> OK
ap=&a;
printf("%s\n",ap->String); // prints 'Adios' -> OK
ap=&b;
printf("%s\n",ap->String); // prints 'IIIIIIIIIIIIIIIIIIIIByeBye' ->
Strange! Why?

Here you access the uninitialized char array of b's base class. That's
undefined behaviour.

It's like this:

int main()
{
int i;
printf("%d", i); // this might output strange numbers or
// crash your system
}

Always initialize your variables.
Also, don't use char arrays and strcpy for strings, use std::string.
 
J

jo

Thomas said:
Here you initialize the char array of a.


Here you initialize one char array of b. The char array of b's base
class is left uninitialized. Accessing it yields undefined behaviour.




Here you access the uninitialized char array of b's base class. That's undefined behaviour.

Oh, of course, i'm sorry.

Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,440
Latest member
YoungBorel

Latest Threads

Top