Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
why does base class pointer pointing to derived class object still points to base class function, if the functions are not declared as virtual
class Base
{
public:
void draw() { cout << "base" << endl; }
virtual void fun() { cout << "base class function" << endl; }
};
class Derived : public Base
{
public:
void draw() { cout << "derived" << endl; }
void fun() { cout << "derived function" << endl; }
};
int main()
{
Derived d;
d.draw(); //derived
Base *b = &d;
b->draw(); //base
b->fun(); //derived function
return 0;
}
b is a pointer pointing to derived object even then why does b->draw() gives output as "base" but not "derived" ?
The function will have to be virtual to be overridden. That's what virtual means: that it can be overloaded.
In C++, non-virtual class functions and class variables (i.e. instance variables or fields) are called by class of pointer, not class of object. Java methods are virtual by default
The whole point of the virtual keyword is to decide whether re-definition of a function in a derived class means:
virtual: actual redefinition of the existing function interface
non-virtual: just another unrelated member function with the same signature
In the second case, the actual function you call with:
d.draw();
b->draw();
are defined by the compile-time type of the object you call it on, i.e. a Base instance will call Base::draw, whereas a Derived instance will call Derived::draw. Note that you can also statically call the base-defined method with the same name using:
d.Base::draw();
Related
This question already has answers here:
Difference between calling of virtual function and non virtual function?
(5 answers)
Virtual dispatch implementation details
(3 answers)
Closed 8 months ago.
I googled and learnt the differences between function hiding and function overriding.
I mean I understand the output of testStuff(), which is seen in the below code snippet.
But what confuses me is that a instance of derived class could be assigned to a reference of the base class. And calling the overriding function through the said reference finally invoking the function of the derived class other than the base class.
Could somebody shed some light on this matter?
Here is the code snippet:
#include <iostream>
using namespace std;
class Parent {
public:
void doA() { cout << "doA in Parent" << endl; }
virtual void doB() { cout << "doB in Parent" << endl; }
};
class Child : public Parent {
public:
void doA() { cout << "doA in Child" << endl; }
void doB() { cout << "doB in Child" << endl; }
};
void testStuff() { //I can understand this function well.
Parent* p1 = new Parent();
Parent* p2 = new Child();
Child* cp = new Child();
p1->doA();
p2->doA();
cp->doA();
p1->doB();
p2->doB();
cp->doB();
}
int main()
{
Child cld;
Parent prt = cld;
Parent &ref_prt = cld;
prt.doA();
ref_prt.doA();
prt.doB();
ref_prt.doB(); //The one which most surprised me! I know `Child::doB()` overrides `Parent::doB()`. And I understand the output for `testStuff()`.
//But I still do not understand this line and `Parent &ref_prt=cld`.
return 0;
}
Here is the output:
doA in Parent
doA in Parent
doB in Parent
doB in Child
But what confuses me is that a instance of derived class could be assigned to a reference of the base class. And calling the overriding function through the said reference finally invoking the function of the derived class other than the base class.
It is indeed exactly like that.
If a member function is virtual in a class, then calling it through a pointer-or-reference to that class will result in a dynamic dispatch, so if the actual object is of a derived class which overrides that function (btw, it neededn't declare it virtual because it's already virtual; and it'd better delcare it override, so that it errors out if it doesn't really override, e.g. because you mistyped the name), than that override will be called.
Tha page linked above should sufficient to shed light on this as well as other doubts.
I am new to C++ and currently I am studying polymorphism.
I have this code:
#include <iostream>
class Base
{
public:
void say_hello()
{
std::cout << "I am the base object" << std::endl;
}
};
class Derived: public Base
{
public:
void say_hello()
{
std::cout << "I am the Derived object" << std::endl;
}
};
void greetings(Base& obj)
{
std::cout << "Hi there"<< std::endl;
obj.say_hello();
}
int main(int argCount, char *args[])
{
Base b;
b.say_hello();
Derived d;
d.say_hello();
greetings(b);
greetings(d);
return 0;
}
Where the output is:
I am the base object
I am the Derived object
Hi there
I am the base object
Hi there
I am the base object
This is not recognizing the polymorphic nature in the greetings functions.
If I put the virtual keyword in the say_hello() function, this appears to work as expected and outputs:
I am the base object
I am the Derived object
Hi there
I am the base object
Hi there
I am the Derived object
So my question is:
The polymorphic effect is retrieved when using a pointer/reference?
When I see tutorials they will present something like:
Base* ptr = new Derived();
greetings(*ptr);
And I was wondering if had to always resort to pointers when using polymorphism.
Sorry if this question is too basic.
For polymorphic behavior you need 2 things:
a virtual method overridden in a derived class
an access to a derived object via a base class pointer or reference.
Base* ptr = new Derived();
Those are bad tutorials. Never use owning raw pointers and explicit new/delete. Use smart pointers instead.
Just add a virtual declaration to the method to allow it to be overridden when using references to the base class:
virtual void say_hello() {...}
in both classes (or at least just the base class).
This question already has answers here:
Downcasting using the 'static_cast' in C++
(3 answers)
Closed 3 years ago.
I have the below piece of code where I have a base class and a derived class. Both base class and derived class are having a function member sharing the same name. In the main(), I have typecasted a base class object to a derived class pointer and trying to call the function. To my utter surprise, it is calling the derived class function member. As far as I know, the base class object won't be having any information about the derived class object. So, how come my derived class pointer is still able to access the derived member function?
In the case of upcasting, I do understand derived class object will be having the contents of the base class that's why a base class pointer pointing to a derived class object will work as expected.
Can someone please help me in understanding how the derived class member function is getting called in this even when I am having a derived class pointer pointing to a base class object(which is having no information of derived class)?
#include<iostream>
using namespace std;
class base
{
public:
void b()
{
cout << "base";
}
};
class derived:public base
{
public:
void b()
{
cout << "derived";
}
};
int main()
{
base b;
derived * d1;
d1 =static_cast<derived*>(&b);
d1->b();
return 0;
}
In your specific case, it's perfectly normal that b is called.
You have a pointer to Derived class, b it's not virtual. So the compiler will generate a call to Derived::b method.
Now, when b will be executed, as you put crap in the this pointer, it's undefined behavior.
But in your case, as you do not access the this pointer, there's no probleme.
Cast a base class to derived class results undefined behavior
As I know, the function doesn't takes any extra space in memory, it stores like the normal function. You can see a member function as a normal function with an extra this pointer. In general, which function to call is determined by the type of the object pointer. But the virtual function is different, it is called by virtual function table, in your code, there is no virtual function declared. So there is no virtual function table.
You can see your code in a different way:
void derived_b(derived* this)
{
cout << "derived";
}
void base_b(base* this)
{
cout << "base";
}
int main()
{
base b;
derived * d1;
d1 =static_cast<derived*>(&b);
derived_b(d1);
return 0;
}
If you define some member in class, and use it in function b, it may cause some error.like
class base
{
public:
void b()
{
cout << "base";
}
};
class derived:public base
{
int a;
public:
derived(){a = 1;}
void b()
{
cout << "derived" << a;
}
};
your code in main() may cause error because the object b don't have any member in memory.
This question already has answers here:
What is object slicing?
(18 answers)
Closed 8 years ago.
I checked this code, and i saw that by the end of the function func()
the destructor of base class have been called twice.
I dont understand why??
thank you..
class base {
public:
base(){cout << "ctor of base\n";}
~base(){cout << "d-ctor of base\n";}
};
class derived: public base
{
public:
derived(){cout << "ctor of derived\n";}
~derived(){cout << "d-ctor of derived\n";}
};
void func(base ob)
{
cout << "inside func\n";
}
void main()
{
derived ob;
func(ob);
system("pause");
}
Refactoring your base class like this:
class base {
public:
base(){cout << "ctor of base\n";}
base(const base&) {cout << "copy-ctor of base\n";}
~base(){cout << "d-ctor of base\n";}
};
would issue the following output:
ctor of base
ctor of derived
copy-ctor of base
inside func
d-ctor of base
d-ctor of derived
d-ctor of base
Showing pretty clearly your base variable inside func was copied and then destroyed.
base is passed by value to func.
This means a sliced copy of ob will be created.
This will be destroyed as well as ob itself. The destructor of ob (derived::~derived) will automatically call the base classes destructor.
Therefore the base destructor is called two times.
When you call the function you take the parameter by value. Therefore you create a local variable of type base in func.
When you return from func, the local variables are destroyed, so ob's descrutor (which has type base is called.
You have to pass polymorphic types via reference or pointer.
This is called the slicing problem. See this link for details.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I understood what is virtual function and pure virtual function but, what is the use of virtual function in C++. Can I get a more apt example for this concept in which virtual function can be used?
The example given for this is
1.Shape a base class
2.Rectangle and square be the derived class
My question is what is the need for shape derived class in first place?
Why cant we directly uses rectangle and square class directly
You can use virtual function to achieve runtime polymorphism.
You can use virtual functions when you want to override a certain behavior(read method) for your derived class than the one implemented for the Base class and you want to do so at run-time through an pointer to Base class.
Example:
#include <iostream>
using namespace std;
class Base {
public:
virtual void NameOf(); // Virtual function.
void InvokingClass(); // Nonvirtual function.
};
// Implement the two functions.
void Base::NameOf() {
cout << "Base::NameOf\n";
}
void Base::InvokingClass() {
cout << "Invoked by Base\n";
}
class Derived : public Base {
public:
void NameOf(); // Virtual function.
void InvokingClass(); // Nonvirtual function.
};
// Implement the two functions.
void Derived::NameOf() {
cout << "Derived::NameOf\n";
}
void Derived::InvokingClass() {
cout << "Invoked by Derived\n";
}
int main() {
// Declare an object of type Derived.
Derived aDerived;
// Declare two pointers, one of type Derived * and the other
// of type Base *, and initialize them to point to aDerived.
Derived *pDerived = &aDerived;
Base *pBase = &aDerived;
// Call the functions.
pBase->NameOf(); // Call virtual function.
pBase->InvokingClass(); // Call nonvirtual function.
pDerived->NameOf(); // Call virtual function.
pDerived->InvokingClass(); // Call nonvirtual function.
}
Output will be:
Derived::NameOf
Invoked by Base
Derived::NameOf
Invoked by Derived