jmasterx
jmasterx

Reputation: 54183

Can this be done?

I was wondering if the following was possible:

class foo
{
  virtual void bar();
}

class izy : public foo
{
 int a;
 virtual  void bar()
 {
  a = 2;
 }
}

foo *anyfoo = new izy;
anyfoo.bar();

essentially what I want to know is, can I add the variable a or will a be nonexistant since its not part of the base class foo?

Upvotes: 1

Views: 150

Answers (6)

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99695

In your code you will call foo::bar(). To call a function which will modify a (izy::bar) you should make bar virtual.


After you've made bar virtual your code will change a if you'll move bar to the public section. anyfoo is points to the instance of izy class, which contains a.

Upvotes: 1

Rup
Rup

Reputation: 34418

can I add the variable a or will a be nonexistant since its not part of the base class foo?

What the other answers haven't quite said yet: your variable isn't a foo, you have a foo*. It's a pointer to some other area of memory of indeterminate size. So you're not restricted to storage size of a foo so yes you can have any amount of extra storage.

If you allocated your variable as a foo with foo storage you can't shoehorn in more, i.e.

foo anyFoo;
((bar*)(&anyFoo))->bar();

won't work.

Upvotes: 0

JustJeff
JustJeff

Reputation: 12980

Inheritance allows new variables in derived classes. What you are trying to achieve is polymorphism, which is prevented in this case by using a pointer to the base class type.

Upvotes: 1

Muhit
Muhit

Reputation: 787

Yes you can add new property like functions and variables.Inheritance allows you to use public and protected properties of parent class. As well can over read those properties as you did for the bar() function.

Thanks

Upvotes: 0

mhshams
mhshams

Reputation: 16972

yes, you can add new Variables and Methods in subclasses.

Upvotes: 3

sepp2k
sepp2k

Reputation: 370435

With the code you have, it will not work as you want because foo's bar will be called, not izy's bar. If you change bar to be virtual, it will work as intended. a only existing in the izy class is not a problem.

Upvotes: 1

Related Questions