Changing signature while Overriding in C++ - c++

I have a base class
class Shape{
public:
virtual int getArea()=0;
}
I want to change the signature while overriding like this:
class Rectangle : class Shape{
public:
int getArea(int someParameter = 0){
return 0;
}
}
Is it possible somehow to achieve this, as I am using default value for newly added parameter?

The only solution I can see is that you implement both int getArea() and int getArea(int), where one function can call the other (for example int getArea() { return getArea(0); }). You can not have the overload taking an argument have a default argument then.

You need to overload your virtual function. But if you overloaded virtual function, you will get a warning "hides overloaded virtual function"
Solution is override function with native signature and overload it with virtual prefix.
Example:
class A {
virtual void foo(int) {...}
};
class B: public A {
void foo(int i) override {
A::foo(i);
}
virtual void foo(const std::string& str) {
...
}
};

Related

How can I access these functions on the derived class? [duplicate]

How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is derived from parent. Within
each class there is a print function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?
I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).
If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.
class left {
public:
void foo();
};
class right {
public:
void foo();
};
class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();
// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};
Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.
class bottom : public left, public left { // Illegal
};
Given a parent class named Parent and a child class named Child, you can do something like this:
class Parent {
public:
virtual void print(int x);
};
class Child : public Parent {
void print(int x) override;
};
void Parent::print(int x) {
// some default behavior
}
void Child::print(int x) {
// use Parent's print method; implicitly passes 'this' to Parent::print
Parent::print(x);
}
Note that Parent is the class's actual name and not a keyword.
If your base class is called Base, and your function is called FooBar() you can call it directly using Base::FooBar()
void Base::FooBar()
{
printf("in Base\n");
}
void ChildOfBase::FooBar()
{
Base::FooBar();
}
In MSVC there is a Microsoft specific keyword for that: __super
MSDN:
Allows you to explicitly state that you are calling a base-class implementation for a function that you are overriding.
// deriv_super.cpp
// compile with: /c
struct B1 {
void mf(int) {}
};
struct B2 {
void mf(short) {}
void mf(char) {}
};
struct D : B1, B2 {
void mf(short) {
__super::mf(1); // Calls B1::mf(int)
__super::mf('s'); // Calls B2::mf(char)
}
};
If access modifier of base class member function is protected OR public, you can do call member function of base class from derived class.
Call to the base class non-virtual and virtual member function from derived member function can be made.
Please refer the program.
#include<iostream>
using namespace std;
class Parent
{
protected:
virtual void fun(int i)
{
cout<<"Parent::fun functionality write here"<<endl;
}
void fun1(int i)
{
cout<<"Parent::fun1 functionality write here"<<endl;
}
void fun2()
{
cout<<"Parent::fun3 functionality write here"<<endl;
}
};
class Child:public Parent
{
public:
virtual void fun(int i)
{
cout<<"Child::fun partial functionality write here"<<endl;
Parent::fun(++i);
Parent::fun2();
}
void fun1(int i)
{
cout<<"Child::fun1 partial functionality write here"<<endl;
Parent::fun1(++i);
}
};
int main()
{
Child d1;
d1.fun(1);
d1.fun1(2);
return 0;
}
Output:
$ g++ base_function_call_from_derived.cpp
$ ./a.out
Child::fun partial functionality write here
Parent::fun functionality write here
Parent::fun3 functionality write here
Child::fun1 partial functionality write here
Parent::fun1 functionality write here
Call the parent method with the parent scope resolution operator.
Parent::method()
class Primate {
public:
void whatAmI(){
cout << "I am of Primate order";
}
};
class Human : public Primate{
public:
void whatAmI(){
cout << "I am of Human species";
}
void whatIsMyOrder(){
Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR
}
};
struct a{
int x;
struct son{
a* _parent;
void test(){
_parent->x=1; //success
}
}_son;
}_a;
int main(){
_a._son._parent=&_a;
_a._son.test();
}
Reference example.

Cannot Instantiate abstract class but class is not abstract / derived method's param

Why I can't create new instance of class which is derived class of my abstract base class? My derived class has overriden base method but with different parametr which is derived class of base class param.
class BaseArg {
} ;
class DerivedArg :public BaseArg{
} ;
class BaseHandler{
public:
virtual void handle(BaseArg* arg) = 0;
} ;
DerivedHandler {
void handle(DerivedArg* arg) {}
} ;
auto x = new DerivedHandler() ;
Compiler returns "Cannot Instantiate abstract class"
Why? In my opinion it should works.
class BaseHandler
{
public:
virtual void handle(BaseArg* arg) = 0;
};
You declare a virtual function handle that needs to be able to accept any kind of BaseArg.
class DerivedHandler : public BaseHandler
{
public:
void handle(DerivedArg* arg) { }
};
Your overriding function just accepts one specific type of BaseArg, so it does not suffice to provide an implementation for the (more general!) inherited function handle. The other way round would have worked (in theory only, see below) – or it would have (truely) worked with return type, as a DerivedArg returned always is a BaseArg, too...
For overview:
class Base
{
public:
virtual void f0(BaseArg* arg) = 0;
virtual void f1(DerivedArg* arg) = 0;
virtual BaseArg* f2() = 0;
virtual DerivedArg* f3() = 0;
};
class Derived : public Base
{
public:
virtual void f0(DerivedArg* arg) override; // FAILS!
virtual void f1(BaseArg* arg) override; // (fine...)(*)
virtual DerivedArg* f2() override; // fine...
virtual BaseArg* f3() override; // FAILS!
};
(*) Actually, this case would have been fine in theory. C++, however, does not support contravariant function arguments, so this case will fail, too (the new function considered being an overload only)!
For more information, have a look at Wikipedia.

How to use base class functions in C++ [duplicate]

How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is derived from parent. Within
each class there is a print function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?
I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).
If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.
class left {
public:
void foo();
};
class right {
public:
void foo();
};
class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();
// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};
Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.
class bottom : public left, public left { // Illegal
};
Given a parent class named Parent and a child class named Child, you can do something like this:
class Parent {
public:
virtual void print(int x);
};
class Child : public Parent {
void print(int x) override;
};
void Parent::print(int x) {
// some default behavior
}
void Child::print(int x) {
// use Parent's print method; implicitly passes 'this' to Parent::print
Parent::print(x);
}
Note that Parent is the class's actual name and not a keyword.
If your base class is called Base, and your function is called FooBar() you can call it directly using Base::FooBar()
void Base::FooBar()
{
printf("in Base\n");
}
void ChildOfBase::FooBar()
{
Base::FooBar();
}
In MSVC there is a Microsoft specific keyword for that: __super
MSDN:
Allows you to explicitly state that you are calling a base-class implementation for a function that you are overriding.
// deriv_super.cpp
// compile with: /c
struct B1 {
void mf(int) {}
};
struct B2 {
void mf(short) {}
void mf(char) {}
};
struct D : B1, B2 {
void mf(short) {
__super::mf(1); // Calls B1::mf(int)
__super::mf('s'); // Calls B2::mf(char)
}
};
If access modifier of base class member function is protected OR public, you can do call member function of base class from derived class.
Call to the base class non-virtual and virtual member function from derived member function can be made.
Please refer the program.
#include<iostream>
using namespace std;
class Parent
{
protected:
virtual void fun(int i)
{
cout<<"Parent::fun functionality write here"<<endl;
}
void fun1(int i)
{
cout<<"Parent::fun1 functionality write here"<<endl;
}
void fun2()
{
cout<<"Parent::fun3 functionality write here"<<endl;
}
};
class Child:public Parent
{
public:
virtual void fun(int i)
{
cout<<"Child::fun partial functionality write here"<<endl;
Parent::fun(++i);
Parent::fun2();
}
void fun1(int i)
{
cout<<"Child::fun1 partial functionality write here"<<endl;
Parent::fun1(++i);
}
};
int main()
{
Child d1;
d1.fun(1);
d1.fun1(2);
return 0;
}
Output:
$ g++ base_function_call_from_derived.cpp
$ ./a.out
Child::fun partial functionality write here
Parent::fun functionality write here
Parent::fun3 functionality write here
Child::fun1 partial functionality write here
Parent::fun1 functionality write here
Call the parent method with the parent scope resolution operator.
Parent::method()
class Primate {
public:
void whatAmI(){
cout << "I am of Primate order";
}
};
class Human : public Primate{
public:
void whatAmI(){
cout << "I am of Human species";
}
void whatIsMyOrder(){
Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR
}
};
struct a{
int x;
struct son{
a* _parent;
void test(){
_parent->x=1; //success
}
}_son;
}_a;
int main(){
_a._son._parent=&_a;
_a._son.test();
}
Reference example.

C++ "overload virtual warning" when implementing interface

Here is my example code:
class Interface {
public:
virtual void foo(const Interface &interface) = 0;
};
class A : public Interface {
public:
void foo(const A &a) {
// do something with another object of same type
}
};
class B : public Interface {
public:
void foo(const B &b) {
}
};
There is a warning:
warning: 'A::foo' hides overloaded virtual function
[-Woverloaded-virtual]
void foo(const A &a) {
^
note: hidden overloaded virtual function 'Interface::foo'
declared here: type mismatch at 1st parameter ('const Interface &' vs
'const A &')
virtual void foo(const Interface &interface) = 0;
How to deal with the problem? Is adding using Interface::foo; in derived class the best solution? I think it's a common problem. Thanks a lot!
void foo(const A &a) does not override void foo(const Interface &interface). While the language allows covariant return types, you can't have covariant parameters as far as I know.
So your void foo(const A &a) is hiding (or at most overloading) the base version of the function.
If you use C++11's override keyword, the compiler should more clearly tell you that you aren't overriding. Or if you try to instantiate an A then it should fail with an error about A being abstract because it hasn't actually overridden foo.
The solution of course is to make the derived versions use the exact same parameter types for foo.
The virtual part of your virtual void foo() function indicates that it can be overridden in a class that inherits Interface. In class A and B, you have used the same function but changed the parameters, which means that the function will be overloaded.
If you want to just override the function in the sub classes, use void foo(const Interface &interface).
For more details on overloading virtual functions see this post: Overloading a virtual function in a child class
Thanks #GargAnkit in comment,Here is my total solotion:
#include <iostream>
#include <string>
using std::cout;
using std::endl;
class Interface {
public:
int compare(const Interface &that) const {
if (this->to_string() < that.to_string()) {
return -1;
} else if (this->to_string() == that.to_string()) {
return 0;
} else {
return 1;
}
}
virtual std::string to_string() const = 0;
};
class A : public Interface {
public:
std::string to_string() const override {
return "A";
}
};
class B : public Interface {
public:
std::string to_string() const override {
return "B";
}
};
int main() {
A a;
B b;
cout << a.compare(b) << endl;
cout << "ok" << endl;
return 0;
}
For a function to be picked as an override of a function in the base class, both function must match exactly - same name, same parameters, same const/volatile qualification. If the function only differ by the qualification, they will be seen as totally non correlated functions, and the base function will not consider as overriden.
example::
**
class A
{
public:
virtual void fun(..)const{}
};
class B:public A
{
public:
void fun(..){} //violation
};
**

Overriding virtual member function containing constant

How can I override a virtual member function of the following type:
virtual AnimalId func(int index) const
where AnimalId is a typedef unsigned int
I tried several ways but either ending up by an error that I don't give output or that I don't have an overrider at all. I saw on some website that maybe I need to use static const in order to do this, but I don't know how.
In order to override method of signature
virtual AnimalId func(int index) const
declared in base class Base, you have to define function with same signature in derived class:
class Derived : public Base {
public:
virtual AnimalId func(int index) const
{
return 43; // I am using 43 because I think this is
// so much underestimated in favor of 42
}
//...
};
Or you can type override kryword to be more explicit:
class Derived : public Base {
public:
virtual AnimalId func(int index) const override
{
return 43 & 45;
}
//...
};
Did you mean something like: (Note, you have to remove override if you compile for C++03)
typedef unsigned int AnimalId;
class Base
{
public:
virtual ~Base() {}
virtual AnimalId func(int index) const { return 0; }
};
class Derived : public Base
{
public:
AnimalId func(int index) const override { return 42; }
};