This question already has answers here:
Why do we need virtual functions in C++?
(27 answers)
Closed 6 years ago.
In c++, the virtual function in base class can be overridden in derived class.
and a member function where the specific implementation will depend on the type of the object it is called upon, at run-time.
Since virtual function has to be implemented(except for pure virtual)
Can I use regular function in base class and redefine it in derived class?
if yes.
What's the point of using virtual function?
Thanks
You can redefine it but it won't work in a polymorphic way.
so if I have a
class base
{
int foo(){ return 3; }
};
class Der : public base
{
int foo() {return 5;}
};
and then have a function that takes a base
void dostuff(base &b)
{
b.foo(); // This will call base.foo and return 3 no matter what
}
and I call it like this
Der D;
dostuff(D);
Now if I change the base to
class base
{
virtual int foo(){ return 3; }
};
void dostuff(base &b)
{
b.foo(); // This will call the most derived version of foo
//which in this case will return 5
}
so the real answer is if you want to write common code that will call the correct function from the base it needs to be virtual.
Actually, Virtual function is base of object oriented language.
In java, all functions are virtual function.
But in c++, virtual function is slower than regular function.
So if there is no need to function override, you should use regular function instead of virtual function.
Related
This question already has answers here:
Can a class member function template be virtual?
(15 answers)
Closed 1 year ago.
Can i write a class like this:
class Base {
template <typename...Args>
virtual double calculate(const Args&...args) = 0;
};
then i want to write derived class like this:
class Derived1 : public Base {
double calculate(int a) {
}
};
class Derived2 : public Base {
double calculate(int a, int c) {
}
};
if this is not possible, is there any methods can achieve this?
No. Virtual functions can not be templates at all. That applies to any template (variadic or not), and all virtual functions - pure or not.
If you think about it, it makes sense. Template is not a function, it is a template by which compiler will make a function when it is called. A virtual function, on the other hand, have to be a real function, which compiler calls through function pointer to achieve polymorphic behavior.
This question already has answers here:
Why does an overridden function in the derived class hide other overloads of the base class?
(4 answers)
Closed 5 years ago.
I'm normally a C# guy, and it handles this fine, largely under its handling of "best match" resolving the method to call. I'm trying to do something similar in C++ now, but am getting a compile error. Long story short, it's a combination of method overloading and overriding.
class Bar : public Foo { } //Contents don't really matter here
class Base
{
public:
virtual void Do(Foo* foo) { }
virtual void Do(Bar* bar) { }
};
class Derived : public Base
{
public:
virtual void Do(Bar* bar) { }
}
Foo* foo = new Foo();
Derived* d = new Derived();
d->Do(foo); //cannot initialize a parameter of type 'Bar*' with an rvalue of type 'Foo*'
So, it tries to resolve the method against only the methods in Derived rather than recognizing the base class implements a valid match. Again, C# finds the base method. Can C++ not do this, or am I missing something?
A function in a derived class hides any functions of the same name in a base class (even if you're overriding a virtual function). To unhide the other overloads, use a "using" statement:
class Derived : public Base
{
public:
virtual void Do(Bar* bar) { }
using Base::Do;
};
This question already has answers here:
Public virtual function derived private in C++
(3 answers)
Closed 6 years ago.
let's assume u have a class base and class A which inherits from base . base have a declaration of a pure virtual functions called getValue() which is public , and A contains the definition(implementation) of the functions which is set as private .
When trying to use the function getValue() from base reference or pointer (base& /base*) to an A object it access it even though it's declared as private
Because in C++, virtuality and access are orthogonal concerns. When the compiler sees a base* or base& and it needs to call getValue on it, then it's sufficient that the function is accessible in base.
The fact that A declares its (overriding) getValue as private is irrelevant. After all, how could it be relevant? When base.getValue() or base->getValue() is called, you don't know that you might be dealing with an A. That's the whole point of object-oriented programming in the first place!
This does not mean that it's good style to vary access specifiers within a class hierarchy, though, because it can be confusing. In fact, you should split your getValue into two different functions, one being virtual and the other one non-virtual.
Long story: C++ behaves very different from other popular programming languages here, because it actually allows and encourages private virtual functions. Virtual member functions should be private by default, and public member functions should be non-virtual by default, and call the private virtual ones if necessary. (The only exception is the destructor, of course.) Herb Sutter once called this the Non-Virtual Interface Idiom.
Example:
#include <iostream>
class Base
{
public:
virtual ~Base() {}
int getValue() const
{
int const value = doGetValue();
if (value < 0)
{
// error
}
return value;
}
private:
virtual int doGetValue() const = 0;
};
class A : public Base
{
private:
int doGetValue() const override
{
return 123;
}
};
int main()
{
Base* ptr = new A; // use std::unique_ptr in real code
std::cout << ptr->getValue() << "\n";
delete ptr;
}
This question already has answers here:
Differentiate between function overloading and function overriding
(11 answers)
Overloading and overriding
(12 answers)
Closed 7 years ago.
I am studying c plus plus course in my college and i am unable to differentiate between overriding and overloading of a function can anyone please help me.
Here are two different overloads of foo:
void foo(int);
void foo(char);
Here B::bar is a function override:
class A {
public:
virtual void bar();
};
class B : public A {
public:
void bar() override;
};
overloading means functions with same name having different parameters , it does not really depend whether you are using procedural language or object oriented language you can do overloading. well as far as over riding is concerned it means we are explicitly defining a function that exist in base class in derived class . obviously you need object oriented language to perform over riding as it is done between base and derived classes.
Overloading means declaring more than one function with the same name in the same scope. They must have different parameter types, and the suitable overload is chosen at compile time based on the arguments' static types.
void f(int);
void f(double);
f(42); // selects the "int" overload
f(42.0); // selects the "double" overload
Overriding means that a derived class declares a function that matches a virtual function declared in the base class. Calling the function via a pointer or reference to the base class will select the override at run-time, based on the object's dynamic type.
struct Base {
virtual void f();
};
struct Derived : Base {
void f() override; // overrides Base::f
};
Base * b = new Base; // dynamic type is Base
Base * d = new Derived; // dynamic type is Derived
b->f(); // selects Base::f
d->f(); // selects Derived::f
Overriding means, giving a different definition of an existing function with same parameters,
and overloading means adding a different definition of an existing function with different parameters.
Example:
#include <iostream>
class base{
public:
virtual void show(){std::cout<<"I am base";} //this needs to be virtual to be overridden in derived class
void show(int x){std::cout<<"\nI am overloaded";} //this is overloaded function of the previous one
};
class derived:public base{
public:
void show(){std::cout<<"I am derived";} //the base version of this function is being overridden
};
int main(){
base* b;
derived d;
b=&d;
b->show(); //this will call the derived version
b->show(6); // this will call the base overloaded function
}
Output:
I am derived
I am overloaded
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
C++ : implications of making a method virtual
Why is 'virtual' optional for overridden methods in derived classes?
I wonder, what is documented behavior in the following case:
You have
class A
{
virtual void A()
{
cout << "Virtual A"<<endl;
}
void test_A()
{
A();
}
}
class B: public A
{
void A()
{
cout << "Non-virtual A in derived class"<<endl;
}
void test_B()
{
A();
}
}
A a; B b;
a.test_A();
b.test_A();
b.test_B();
What it supposed to do according to C++ standard and why?
GCC works like B::A is also also virtual.
What shoudl happen in general when you override virtual method by non-virtual one in derived class?
The sub-class member function is implicitly virtual if a virtual base-class member function with the same name and signature exists.
The code should not compile as you cannot name a method with the name of the class. But regarding what I understand that is your real question:
Will making a method virtual imply that the same method in all the derived classes is virtual even if the virtual keyword is not present?
The answer is yes. Once a method is declared virtual in a class, then all overrides of that method will be virtual, and the virtual keyword is optional in derived classes (even if I recommend typing it, if only for documentation purposes). Note that for a method in a derived class to be an override it has to have the same name and signature, with only potential difference being a covariant return type:
struct A {};
struct B : A {};
struct base {
virtual A* foo();
virtual A* bar();
};
struct derived : base {
virtual B* foo(); // override, covariant return type
virtual int bar(); // not override, return type is not covariant
virtual A* bar(int); // not override, different argument list
};
This code is ill-formed. A constructor cannot have a return type (as you have done for the constructor of 'A'). Also a constructor cannot be virtual.
After fixing A's constructor, class B is ill-formed as the constructor of A is private.
So, there are many problems with this code (including missing semicolons at the class definitions).
According to standard it should be
A a; B b;
a.test_A(); //"Virtual A"
b.test_A(); //Non-virtual A in derived class
b.test_B(); //Non-virtual A in derived class