i have a problem in properly handling method overriding where an abstract class is present
inside my classes hierarchy.
I'll try to explain:
class AbstractClass{
public:
virtual void anyMethod() = 0;
};
class A : public AbstractClass {
void anyMethod() {
// A implementation of anyMethod
cout << "A";
}
};
class B : public AbstractClass {
void anyMethod() {
// B implementation of anyMethod
cout << "B";
}
};
AbstractClass *ptrA, *ptrB;
ptrA = new A();
ptrB = new B();
ptrA->anyMethod(); //prints A
ptrB->anyMethod(); //prints B
Ok..previous example work fine .. the concrete implementation of the AbstractClass
method anyMethod will be called at run time.
But AbstractClass is derived from another base class which has a method not virtual
called anyMethod:
class OtherClass {
public:
void anyMethod() {
cout << "OtherClass";
}
};
class AbstractClass : public OtherClass {
public:
virtual void anyMethod() = 0;
};
//A and B declared the same way as described before.
Now , if i try something like that:
ptrA = new A();
ptrB = new B();
ptrA->anyMethod(); //prints OtherClass
ptrB->anyMethod(); //prints OtherClass
What am I misunderstanding?
Is there any solution for making ptrA and ptrB printing A and B without using cast, typeid, etc?
Why don't you do:
class OtherClass
{
public:
virtual void anyMethod()
{
cout << "OtherClass";
};
}
That should solve your problems
If anyMethod was declared virtual in the base class to which you have a pointer or reference, it should be looked up virtually and print A and B correctly. If it wasn't, then there is nothing you can do (beyond changing it to be virtual).
I think that if the method in OtherClass that you want to override in A and B is NOT virtual, then the override is not implicit.
I believe there's a way to Explicitly override the functions, look that up.
DeadMGs answer is of course correct. But, if you cannot change OtherClass Methode (e.g. it's from a third party lib) you might want to try this:
Are the pointers ptrA and ptrB of type OtherClass or AbstractClass in your lower example?
If they are OtherClass I would expect the behaviour you described. You could try casting the pointer to AbstractClass then:
dynamic_cast<AbstractClass*>(ptrA)->anyMethod();
As far as I can see from your code OtherClass::anyMethod() is not a virtual and already implemented. It should work as you described if you define it as virtual
I think that your declaration for the second case is:
OtherClass* ptrA; and not AbstractClass *ptrA;
if you declared like the first case , there's no problem because the method is virtual,but if you declare as OtherClass , the compiler will not find virtual and bind to the adress of this method without using vtble.
thanks for the answers.. helped me a lot to understand the problem.
In effect I posted some wrong code, because i was misunderstanding the real problem.
Anyway, i think i partially solved my problem.
Here's the code:
#include <iostream>
`` using namespace std;
class Other{
public:
void foo(){
cout << "Other\n";
}
void foo(int a){}
};
class Abstract : public Other{
public:
virtual void foo() {};
virtual void foo(int c){
Other::foo(c);
}
};
class A : public Abstract{
public:
void foo(){
cout << "A\n";
}
};
class B : public Abstract{
public:
void foo(){
cout << "B\n";
}
};
int main(){
cout << "main\n";
Abstract * ptrA = new A();
Abstract * ptrB = new B();
Other *o = new Other();
o->foo();
ptrA->foo();
ptrB->foo();
ptrB->foo(3); //can't no more use the method foo with different signatures implemented in the base class Other, unless I explicitly redefined in the class Abstract
dynamic_cast<Other*>(ptrB)->foo(3);//can't dynamic_cast from derived to base
I was making two errors:
In my real code (not the simplified version posted before) i forgot to declare virtual
the function foo()
Even declaring virtual wasn't enough. In fact all the implementations of that function must be wrapped inside the class Abstract to become visible to the subclasses A and b. Otherwise wont't compile.
I don't know if it could be a clean solution..in fact that way I need to wrap all foo method signatures.
Related
I have a base class which serves as an interface (if I use that word correctly). The idea is that the base class has some derived classes that implement one virtual function of the base class. Then I also need another class that extends the base class (lets call it extended base). What I would like is that I can store a class derived from base into an extended base pointer.
MWE:
class Base {
public:
virtual ~Base();
virtual double value();
}
class Derived : public Base{
public:
double value() override {return 5;}
}
class ExtendedBase : public Base {
public:
virtual ~ExtendedBase ();
virtual double value2(){return 10;}
}
int main() {
ExtendedBase * object;
object = new Derived();
std::cout << object->value(); //should give implementation in Derived, i.e. 5
std::cout << object->value2(); //should give implementation in ExtendedBase, i.e. 10
delete object;
return 0;
}
With this MWE I get a compile error at the second line in the main. error: cannot convert 'Derived*' to 'ExtendedBase*' in assignment object = new Derived();. Part of me understands why it doesn't work (although I can't explain), but I would like to know if I can get the desired behaviour in some other way.
P.S. Sorry about the bad question name, I couldn't think of another way to keep it short
P.S.2 I know raw pointers like this are not advised. In the future I will change to smart pointers but I don't think they are needed for this simple example
ExtendedBase and Derived are each derived from Base. If you want to use an ExtendedBase* pointer to point to a Derived object, you will need to derive Derived from ExtendedBase.
To use a different example,
class Feline{
virtual void run();
}
class Housecat : Feline{
void run() {}
}
class BigCat : Feline{
virtual void run();
virtual void roar();
}
Here Feline, Housecat, and BigCat are analogous to Base, Derived, and ExtendedBase. BigCat and Housecat are each Feline, but since Housecat is not a BigCat, you can't use a BigCat* pointer to point to a Housecat.
This is the desired behavior from a language architect perspective.
For instance, if you have
class Ship
{
public:
virtual void move() = 0;
}
class Steamboat : public Ship
{
public:
virtual void move() override { ... }
}
class Sailboat : public Ship
{
public:
virtual void move() override { ... }
virtual void setSails() { ... }
}
Now, you don't want a Steamboat to become a Sailboat all of a sudden, hence:
Steamboat* tootoo = new Sailboat;
cannot be valid.
That's why your code cannot work. Conceptually.
So giving a quick fix is not possible, because your concept is not really clear.
When you are assigning an address to a pointer that means you should be able to access all the members of the type the pointer is pointing to through the pointer.
For ex,
class B {};
class D : B {};
B *p = new D();
now through p, at least you can access all the members of base portion of the derived class.
But in your code,
ExtendedBase * object;
object = new Derived();
object should be able to access all the members of ExtendedBase portion of the derived class. But how is it possible as derived class is not derived from ExtendeBase. So compiler is throwing error.
You need to do some changes in your code to work.
To make base as interface (abstract class), you need to define at
least one member function as pure virtual.
If you want to access the member function of ExtendedBase through
Base pointer, you should define same function 'val' in your
ExtendedBase.
Below are the changes.
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() {};
virtual double value() = 0;
};
class Derived : public Base{
public:
~Derived() {};
double value() {
return 5;
}
};
class ExtendedBase : public Base {
public:
virtual ~ExtendedBase () {};
double value()
{
return 10;
}
};
int main() {
Base *p = new Derived();
std::cout << p->value() << std::endl;
delete p;
Base *p1 = new ExtendedBase();
std::cout << p1->value() << std::endl;
delete p1;
return 0;
}
I have this code:
#include <iostream>
using namespace std;
class FooA {
public:
virtual void meth () {cout << "hiA\n";}
};
class FooB : public FooA{
public:
void meth () {cout << "hiB\n";}
};
class FooC : public FooB {
public:
void meth () {cout << "hiC\n";}
};
int main() {
FooA a;
a.meth();
FooB b;
b.meth();
FooC c;
c.meth();
FooA* ptr = &a;
ptr->meth();
ptr = &b;
ptr->meth();
ptr = &c;
ptr->meth();
FooB* ptrB = &b;
ptrB->meth();
ptrB = &c;
ptrB->meth();
}
The output is this:
hiA
hiB
hiC
hiA
hiB
hiC
hiB
hiC
The code is basic and self-explanatory. I tried different combinations of making meth() in each class virtual or not. This will change how the output, obviously, especially if FooA::meth() is not declared as virtual. I have come to the conclusion that it is probably best and most clear to just make every instance of that method virtual. Is there any reason not to?
Edit:
I have another question. When you declare a class, and then define it outside of the class declaration, using ::
Like this
class Foo{
public:
virtual void bar();
};
void Foo::bar {
cout << "Hello";
}
Why can't I do something like
virtual void Foo::bar {
cout << "Hello";
}
Is there any reason not to?
It's superfluous.
If you have a method in a base class declared as virtual, this virtuality will be "inherited" by the overriding method.
Other than that, maybe for documentation purposes it might be acceptable. However, remember that the best virtuals are private, employ the non-virtual interface idiom.
With that done, the "for documentation" reason falls to the ground, since private methods need no public documentation.
Yes, when you don't want a derived class to override the implementation of meth() for some reason.
If you think a derived class might need to change the implementation of meth(), make the method virtual.
Sample code
#include <iostream>
using namespace std;
class Base
{
public:
virtual void Func()
{
cout << "\nIn base func";
}
};
class Derived : public Base
{
public:
void Func()
{
cout << "\nIn derived";
}
};
class Derived2 : public Derived
{
public:
void Func()
{
cout << "\nIn derived2";
}
};
int main()
{
Base* lnewbase = new Derived2();
lnewbase->Func();
return 0;
}
As an example, in the above code, I do not want Func() of Derived to be inherited (seal in C#) which is why there is no virtual keyword although I am aware that it does not change anything in this case. Is there any way to disallow that function to be inherited while making sure it remains a public method?
No; C++ has no equivalent to C#'s sealed modifier.
There is nothing you can do.
Once you make a function in a base class virtual, there's nothing that can be done to get rid of that aspect of it. I can only think of a few things to almost get around it:
Don't make it virtual;
Make a new, public, non-virtual function in Derived that does what you need.
However, in either case, Derived2 will still be able to make its own version of Func(), which will give you the same problem.
I was asked this crazy question.
I was out of my wits.
Can a method in base class which is declared as virtual be called using the base class pointer which is pointing to a derived class object?
Is this possible?
If you're trying to invoke a virtual method from the base class pointer, yes.
That's polymorphism.
If you're asking, with a base class pointer to a derived class, can you invoke a base class method that is overriden by the derived class? Yes that's also possible by explicitly scoping the base class name:
basePtr->BaseClass::myMethod();
Try:
class A { virtual void foo(); }
class B : public A { virtual void foo(); }
A *b = new B();
b->A::foo ();
You mean something like this. (Where pBase is of type pointer-to-base but the pointed-to object is actually of type Derived which is derived from Base.)
pBase->Base::method();
Yes, it's possible.
Yes -- you have to specify the full name though:
#include <iostream>
struct base {
virtual void print() { std::cout << "Base"; }
};
struct derived : base {
virtual void print() { std::cout << "Derived"; }
};
int main() {
base *b = new derived;
b->base::print();
delete b;
return 0;
}
If I understand the question correctly, you have
class B
{
public:
virtual void foo();
};
class D: public B
{
public:
virtual void foo();
}
B* b = new D;
And the question is, can you call B::foo(). The answer is yes, using
b->B::foo()
class B
{
public:
virtual void foo();
};
class D: public B
{
public:
virtual void foo();
}
B* b = new D;
Try calling
(*b).foo()
to invoke base class foo function
class B {
public: virtual void foo();
};
class D: public B {
public: virtual void foo()
{
B::foo();
};
}
B* b = new D;
Solutions :
b->foo();
b->B::foo()
OR do not override/define foo() in the derived class D and call b->foo()
B objb = *b; objb.foo() ; // this is object slicing and not (*b).foo() as in one of the previous answers
No. Not in a clean way. But yes. You have to do some pointer manipulation, obtain a pointer to the vtable and make a call. but that is not exactly a pointer to base class, but some smart pointer manipulation. Another approach is using scope resolution operator on base class.
In my class design I ran into the following problem:
class MyData
{
int foo;
};
class AbstraktA
{
public:
virtual void A() = 0;
};
class AbstraktB : public AbstraktA
{
public:
virtual void B() = 0;
};
template<class T>
class ImplA : public AbstraktA
{
public:
void A(){ cout << "ImplA A()"; }
};
class ImplB : public ImplA<MyData>, public AbstraktB
{
public:
void B(){ cout << "ImplB B()"; }
};
void TestAbstrakt()
{
AbstraktB *b = (AbstraktB *) new ImplB;
b->A();
b->B();
};
The problem with the code above is that the compiler will complain that AbstraktA::A() is not defined.
Interface A is shared by multiple objects. But the implementation of A is dependent on the template argument. Interface B is the seen by the outside world, and needs to be abstrakt.
The reason I would like this is that it would allow me to define object C like this:
Define the interface C inheriting from abstrakt A.
Define the implementation of C using a different datatype for template A.
I hope I'm clear. Is there any way to do this, or do I need to rethink my design?
You have two paths of inheritance from AbstracktA, you implement AbstraktA::A() only in one of them, so the compiler complains.
You probably want to inherit virtually from AbstraktA in both case so that there is only one AbstraktA base object (add virtual before AbstraktA).
I forgot to add virtual destructors to the base classes. This leads to runtime malloc errors I believe.
AbstraktB *b = new ImplB;
b->A();
b->B();
delete b;
In debug mode, at the delete statement, GCC gives me:
malloc: *** error for object 0x60e2c4: pointer being freed was not allocated
I solved this by changing the base classes to:
class AbstraktA
{
public:
virtual ~AbstraktA(){};
virtual void A() = 0;
};
class AbstraktB : virtual public AbstraktA
{
public:
virtual ~AbstraktB(){};
virtual void B() = 0;
};