Unsolved How to set the right method
-
Hello guys , i have a question and this is an exemple to understand my question
class A { A(); ~A(); virtual void test(); ;} class B :public A{ B(); ~B(); virtual void test(); ;} class C:public A { C(); ~C(); virtual void test(); ;}
as you see , i m using Heritage her , for exemple
B.test()
will call the method in class B ,
Now if i write Alonetest(); //
Which method test() he will call ? the A,B or C?
-
Hi
since its a member function, you need a class instance to call it.
so
test(); //
wont work. -
-
@JonB an if i delete the object , for exemple
B *b=new B(); delete b; test(); // this will work ?
-
@Zunneh
hi
Nope. There is no way to call a normal member function without the object.
Why do you want to do this ?
you could just have a normal non class function then. -
This works, if he calls test() inside the B class (e.g. constructor).
@Zunneh
Where do you want to call the test()-function?Back to your question: B inherits from A, C inherits from A. Because "test" is a virtual function in A, it will call the test()-function in B, but of course your function call wont work :)
-
@Pl45m4 said in How to set the right method:
This works, if he calls test() inside the B class
No, it doesn't. Constructor is a method of a class also. So, if you call a method inside the constructor you're calling it with a class instance already (not necessarily completely constructed one though).
This does not make any sense in C++ (if test() is a method of B or a base class of B), not even for static methods:B *b=new B(); delete b; test();
@Zunneh You simply can't call a non-static method without a class instance. You can have a static method, then you don't need an instance:
class B { public: static void test() {} }; B::test();
-
I meant if he calls it in constructor, he doesn't have to "B->test ()".
But yeah, to call the constructor, you'll need an object instance first :) -
@Zunneh
To understand what the virtual term, i suggest you to read this IBM article.Static vs Dynamic Binding
https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_72/rzarg/cplr139.htmVirtual functions are dynamically bound, meaning that the particular
function called is determined by the dynamic type of the object
through which it’s invoked (Mayer S. Effective C++: 55 Specific Ways to Improve Your Programs and Designs. Third edition. p. 181)A *a = new A(); B *b = new B(); a->test() // call A::test() b->test() // call B::test() a = b; a->test() // call B::test() because A::test() is virtual delete a; delete b;
-
Why you mentioned me?! I know what virtual functions are :)
I guess you meant @Zunneh -
@Pl45m4
Just a little mistake xD.