C++ - unwanted use of base method [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a base class A and a few derived classes B, C and D, that all have a method DoSomething(), which is virtual in the base class method (it's implemented in all sub classes as well as in the base class).
I have a problem, that the derived class B uses the method from the base class A. This may be the result of bad design, but I do not see the problem as the implementation is pretty straight forward.
An object of class B that is created in the following
A* a = new B();
If I call the method DoSomething() for this object, the method of the base class is used:
a->DoSomething(); //Results in Base class method being called.
But I expect/want that the method of class B is used. Can you tell me what's wrong?

According to the symptoms that you describe:
either you have forgotten the virtual keyword in the base class member definition.
or you have a subtle difference in you signature in the derived class.
The way forward would be to indicate in the derived class that the function is an override:
class A {
...
virtual void DoSometing();
};
class D : public A {
...
void DoSomething() override;
};
In this case, in case of mismatch you'll get a clear compiler error message.

The following example implements what you asked for.
#include <iostream>
class A
{
public:
virtual void DoSomething()
{
std::cout << "A::DoSomething" << std::endl;
}
};
class B : public A
{
public:
virtual void DoSomething()
{
std::cout << "B::DoSomething" << std::endl;
}
};
int main(int argc, char **argv)
{
A *a = new B();
a->DoSomething();
delete(a);
return 0;
}
Output:
B::DoSomething

Related

Why is this pure virtual method not compiling? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I use a pure virtual method as shown in the code below.
#include <iostream>
using namespace std;
class Advertisment
{
public:
vitual void price (int Uchrg, int no_of_unt) = 0;
{
}
};
class TVadvertisment : public Advertisment
{
public:
void price (int Uchrg, int no_of_unt)
{
int adPrice = Uchrg * no_of_unt;
cout << "Advertisment Price: " << adPrice;
}
};
int main()
{
TVadvertisment T;
T.price(1000, 60);
return 0;
}
As I know a pure virtual function will be declared as virtual void display() = 0;. But the Code::Blocks compiler show an error because of this = 0. Without that it will compile successfully.
And also I didn't use pointers to call methods of derived class.
Your function is pure virtual, which means the method is virtual and not even implemented in the base class (= 0).
So you have to delete the block after it.
It has to be:
virtual price(int Uchrg, int no_of_unt) = 0;
without the { }.
Virtual means, that classes that inherit from a base class can override the method and called via the base class interface. If a class has a pure virtual method, the class is abstract and this function needs to be overridden by classes that inherit from that base class to be instantiated.
In short:
Virtual:
virtual price(int Uchrg, int no_of_unt)
{
// Implementation
}
Has an implementation is the base class. Sub classes does not need to override, but they can. The class is not abstract and can be instanciated.
Pure virtual:
virtual price(int Uchrg, int no_of_unt) = 0; // No implementation
There is no implementation, the sub classes must override this to be not abstract.
Call a virtual method via base class:
Base* pBase = new Derived;
pBase->fun();
The method is called via the interface of the base class, but it will be the derived class' method.

Inheritance of private members [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
When asked if private members of class B are inherited by D, a class derived from B, people emphatically say: yes they are inherited but not accessible directly, only indirectly for instance via public methods in the base class. OK, but what is the difference between not being inherited and not being directly accessible? For instance class X (NOT derived from B) also has access to private members of B via public methods of B, even though X doesn't inherit anything from B.
what is the difference between
1) not being inherited and
2) being inherited and not being directly accessible.
what is not clear?
The difference is in the class layout.
struct B {
private: char buf[1024];
};
struct D : B { };
Here, sizeof(D) >= sizeof(B). It's still there, i.e. it's clearly inherited.
If the base class has virtual functions that can be overriden by the derived class, clearly this is an important difference to a class having access to a base class instance but not inheriting from it:
class B
{
public:
virtual ~B() {}
int get_a() const
{
do_something();
return a;
}
virtual void do_something() const
{
std::cout << "In B\n";
}
private:
int a{};
};
class D : public B
{
virtual void do_something() const
{
std::cout << "In D\n";
}
};
int main()
{
D d;
d.get_a();
}
If the base class does not have any virtual functions, then the usefulness of inheriting from it is less clear. In fact, it is perhaps best not to inherit from it (at least publicly) as the lack of a virtual destructor could cause some problems, and it should be made a member variable instead.

Throw an exception or return default value in base class [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a base class that defines methods as virtual and those methods has nothing inside, just the declaration. I have a class that derives from the base class and doesn't implements all the methods and here is where the problem appears. If we call a method that isn't implemented on the derived class, but in the base, it crashes.
Example (it crashes):
#include <iostream>
class Foo
{
public:
virtual std::string ref() {}
};
class Bar : public Foo {};
int main(int argc, char ** argv)
{
auto foo = new Bar;
auto bar = foo->ref();
return 0;
}
Q: What is the best solution in this case.
1) - Return a default (empty) value.
virtual std::string ref()
{
return "";
}
2) - Throw an exception that you can't call methods directly from the base class.
virtual std::string ref()
{
throw std::runtime_error(":(");
}
Thank you.
This is what pure virtuals are for:
virtual std::string ref() = 0;
now the compiler won't let you instantiate an instance of a derived type that doesn't define that function.
If we call a method that isn't implemented on the derived class, but
in the base, it crashes.
This does not strictly apply to your example code:
virtual std::string ref() {}
An implementation is there; you get a crash because the implementation doesn't return anything. The same would likely happen here, for example:
#include <string>
std::string f() {}
int main()
{
std::string x = f();
x = "";
}
(I say "likely" because it's undefined behaviour, so the crash is not guaranteed.)
As for your problem:
If you need to call functions which do not conceptually exist, then you have a design problem; chances are that your base class tries to fulfill too many responsibilities at the same time.
Otherwise, use abstract classes. You can make a class abstract by declaring at least one function pure virtual:
class Foo
{
public:
virtual std::string ref() = 0; // pure virtual function
};
Please note three further things:
You almost certainly need a virtual destructor in your base class.
Except of the destructor, consider making your public functions non-virtual and your virtual functions private, the public non-virtual ones calling the private virtual ones.
Your function looks like a candidate for a const function.
Final example:
class Foo
{
public:
virtual ~Foo() {}
std::string ref() const { return refImpl(); }
private:
virtual std::string refImpl() const = 0;
};

What is the use of virtual class and abstract class in C++ [closed]

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

Best way to call hidden base class method [duplicate]

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 9 years ago.
In the following code, "d.Foo()" throws a compiler error claiming that function Foo() does not take 0 arguments. Yet a 0-argument function with that name exists in the base class. The line "d.Base::Foo()" is acceptable.
I have a vague memory of learning that the use of a function name in a derived class hides all functions of that name in a base class, even though arguments may be different. I don't remember why, nor do I remember the best way to avoid that problem. Is my solution best, or is there another way to get at Base::Foo()?
Thanks very much!
RobR
// Override.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
class Base
{
public :
void Foo()
{
}
};
class Derived : public Base
{
public:
void Foo(int x)
{
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Derived d;
d.Foo();
d.Base::Foo();
return 0;
}
you can use(!) base class member functions via using
class Derived : public Base {
public:
using Base::Foo;
};
You could define Derived::Foo() as:
class Derived : public Base {
public:
void Foo() { Base::Foo(); }
};