开发者

Can this be done?

I was wondering if the following was possible:

class foo
{
 开发者_StackOverflow中文版 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?


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


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.


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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜