The compiler keeps saying 'class A' has no member named 'foo'.
I am trying to use a function from a derived class with a pointer. Here is my code:
class A{
.....
};
class B:public A{
virtual void foo() = 0;
};
class C:public B{
....
public:
void foo(){
....
}
};
I have a table of A pointers named Table and when trying
Table[j]->foo()
I am getting the compiler error.
What should I do except cast?
You have a compilation error because function foo is not declared in class A.
You can declare it as pure virtual in A like this:
class A {
virtual void foo() = 0;
};
In derived classes you don't have to declare foo as explicitly virtual. If only C is a concrete class, you don't have to declare foo in class B at all.
If your example if you know that in your array of pointers to A you have only instances of class C you can explicitly cast to pointer to C but it is a sign of poor design and I don't recommend it:
static_cast<C*>(Table[j])->foo()
If you have a pointer to a base and want to access a member of the derived type you have to cast so you have a pointer to the derived type, either that or as in your case add foo() as a virtual member to the base.
class A
{ ... };
class B : public A:{
{
public:
virtual foo() { std::cout << "B::foo" << std::endl; }
};
class C : public B
{
public:
void foo() { std::cout << "C::foo" << std::endl;
};
...
A * arr[8];
for(int i = 0; 8>i; ++i)
arr[i] = new C;
((B*)arr[0])->foo(); // will print "C::foo\n"
But if you added virtual void foo() = 0; to A then you could just do arr[0]->foo() and it would still print C::foo
Related
Can I have a virtual function in the base class and some of my derived classes do have that function and some don't have.
class A{
virtual void Dosomething();
};
class B : public A{
void Dosomething();
};
class C : public A{
//Does not have Dosomething() function.
};
From one of my c++ textbook:
Once a function is declared virtual, it remains virtual all the way down the inheritance, even if the function is not explicitly declared virtual when the derived class overrides it.
When the derived class chooses not to override it, it simply inherits its base class's virtual function.
Therefore to your question the answer is No. Class c will use Class A's virtual function.
Derived classes do not have to implement all the virtual functions, unless it is a pure virtual function. Even in this case, it will cause an error only when you try to instantiate the derived class( without implementing the pure virtual function ).
#include <iostream>
class A{
public :
virtual void foo() = 0;
};
class B: public A{
public :
void foo(){ std::cout << "foo" << std::endl;}
};
class C: public A{
void bar();
};
int main() {
//C temp; The compiler will complain only if this is initialized without
// implementing foo in the derived class C
return 0;
}
I think the closest you might get, is to change the access modifier in the derived class, as depicted below.
But, I would consider it bad practice, as it violates Liskov's substitution principle.
If you have a situation like this, you might need to reconsider your class design.
#include <iostream>
class A {
public:
virtual void doSomething() { std::cout << "A" << std::endl; }
};
class B : public A {
public:
void doSomething() override { std::cout << "B" << std::endl; };
};
class C : public A {
private:
void doSomething() override { std::cout << "C" << std::endl; };
};
int main(int argc, char **args) {
A a;
a.doSomething();
B b;
b.doSomething();
C c;
//c.doSomething(); // Not part of the public interface. Violates Liskov's substitution principle.
A* c2 = &c;
c2->doSomething(); // Still possible, even though it is private! But, C::doSomething() is called!
return 0;
}
My question is why I cannot call protected virtual member function in derived class through a pointer to the base class unless declaring derived class as a friend of base class?
For example:
#include <iostream>
class A {
friend class C; // (1)
protected:
virtual void foo() const = 0;
};
class B : public A {
void foo() const override { std::cout << "B::foo" << std::endl; }
};
class C : public A {
friend void bar(const C &);
public:
C(A *aa) : a(aa) { }
private:
void foo() const override {
a->foo(); // (2) Compile Error if we comment out (1)
//this->foo(); // (3) Compile OK, but this is not virtual call, and will cause infinite recursion
std::cout << "C::foo" << std::endl;
}
A *a;
};
void bar(const C &c) {
c.foo();
}
int main() {
B b;
C c(&b);
bar(c);
return 0;
}
The output is
B::foo
C::foo
In the above code, I want to call virtual function foo() through member a of class C (not the static bound one through this at compile time), but if I don't make C as A's friend, the call is illegal.
I think C is inherited from A, so that it can access the protected member of A, but why is it actually not happen?
Class C can access the protected members of its own base class, but not members of any other A.
In your example, the parameter a is part of the totally unrelated class B to which C has no access rights (unless you make it a friend).
In c++, Is there a standard way to create a function in a base class that can use the variables of derived classes?
class Foo{
private:
int x;
public:
Foo(){
x = 2;
}
void print(){
std::cout << x << std::endl;
}
};
class Derived : public Foo{
private:
int x;
public:
Derived(){
x = 4;
}
};
void main()
{
Derived a;
a.print();
}
This code prints the variable of the base class ( 2 ). Is there a way to make a function used by many derived classes to use the class's private variables without passing them as parameters?
Edit: My intentions are, to avoid writing the same code for each derived class.
For example, I want a get_var() in all, but this function should return the variable of that own class. I know I can make virtual and override, but I was looking for a way that I don't need to write again and again.
No, it is not possible for the base class to access anything in the derived class directly. The only way for a derived class to share anything with its base class is by overriding virtual member functions of the base class.
In your case, however, this is not necessary: the derived class can set variable x in the base class once you make it protected, and drop its own declaration as unnecessary:
class Foo{
protected: // Make x visible to derived classes
int x;
public:
Foo(){
x = 2;
}
void print(){
std::cout << x << std::endl;
}
};
class Derived : public Foo{
public:
Derived(){
x = 4;
}
};
I have stumbled on a problem while trying to re-use code from different classes. I post it here in hope that some of you might be able to help me.
I have a set of classes (B,C) deriving from the same class (A) which forces the implementation of some methods (foo, run). Class B implements these method, and both B and C provide other methods:
#include<iostream>
template<class I, class O>
class A {
public:
A() {}
virtual ~A() {}
virtual void foo() const = 0; // force implementation of this function
virtual void run() const = 0; // force implementation of this function
};
template<class I, class O>
class B : public A<I,O> {
public:
B() {}
virtual ~B() {}
virtual void foo() const { // implementation for the Base class
std::cout << "B's implementation of foo" << std::endl;
}
virtual void run() const { // implementation for the Base class
std::cout << "B's implementation of run" << std::endl;
}
virtual void foobar() const { // some other function provided by this class
std::cout << "B's implementation of foobar" << std::endl;
}
};
template<class I, class O, class M>
class C : public A<I,O> {
public:
C() {}
virtual ~C() {}
virtual void bar(M m) const { // some other function provided by this class
std::cout << "C's implementation of bar with: " << m << std::endl;
}
};
Now, what I am trying to do is inherit from both B and C so that I can have the extra methods (foobar, bar), but also not have to implement the method from class A (foo) because it is already defined in B:
template<class I, class O>
class D : public B<I,O>, public C<I,O,int> {
public:
D() {}
void run() const {
this->bar(123);
this->foo();
this->foobar();
}
};
But for some reason the compiler gives me this error:
test.cpp: In function ‘int main(int, char**)’:
test.cpp:68:35: error: cannot allocate an object of abstract type ‘D<float, double>’
A<float, double> *d = new D<float, double>(); // what I need to do
test.cpp:48:11: note: because the following virtual functions are pure within ‘D<float, double>’:
class D : public B<I,O>, public C<I,O,int> {
^
test.cpp:9:22: note: void A<I, O>::foo() const [with I = float; O = double]
virtual void foo() const = 0; // force implementation of this function
This is the code I use to run it:
int main(int argc, char **argv)
{
A<float, double> *b = new B<float, double>();
b->foo(); // prints "B's implementation of foo"
b->run(); // prints "B's implementation of run"
//A<float, double> *c = new C<float, double, int>(); // obviously fails because C does not implement any of A's functions
//A<float, double> *d = new D<float, double>; // line 68: what I need to do
//d->run(); // ***throws the abstract class error
return 0;
}
I want to use the 'run' function of an object of class D from a pointer to a A. As all the functions are virtual I expect to execute implementation of each function defined in the lowest inheritance point, meaning that 'B::run' will be discarded. As 'D::run' uses functions from both B and C I need to inherit from both classes.
I hope I have described it enough and not confused anybody.
Thanks for the help!
If you change B and C to virtually inherit from the A template class, they will share a single base instance when combined by D and this error will go away:
template<class I, class O>
class B : virtual public A<I,O> {
// ...
template<class I, class O, class M>
class C : virtual public A<I,O> {
However, this pattern (known as the diamond inheritance (anti-)pattern) can be very difficult to reason about and I would strongly suggest avoiding it if possible. You are likely to run into even more obscure problems later.
Here is a sample of this technique working, but showing some results that may not be expected at first glance:
class A {
public:
virtual void foo() = 0;
};
class B : virtual public A {
public:
virtual void foo() override;
};
void B::foo()
{
std::cout << "B::foo()" << std::endl;
}
class C : virtual public A { };
class D : public B, public C { };
int main() {
D d;
C & c = d;
c.foo();
return 0;
}
Note that even though you are calling C::foo(), which is pure virtual, since there is only one A instance the inherited pure virtual function resolves to B::foo() though the shared A vtable. This is a somewhat surprising side-effect -- that you can wind up invoking methods implemented on a cousin type.
The answer by #cdhowie gives you a solution.
To understand the problem the compiler is complaining about, take a set of simpler classes:
struct A
{
virtual void foo() = 0;
};
struct B : A
{
virtual void foo() {}
}
struct C : A
{
void bar() {}
}
struct D : B, C
{
};
The class hierarchy of D is:
A A
| |
B C
\ /
D
With this inheritance structure, D has two virtual tables, one corresponding to the B inheritance hierarchy and one corresponding to C inheritance hierarchy. The difference being that in the B hierarchy, there is an implementation of A::foo() while there isn't one in the C hierarchy.
Let's say you were allowed to construct an object of type D.
D d;
C* cp = &d;
Now cp points to the C hierarchy of D, and uses a virtual table in which foo is not implemented. That will be a run time error that the compiler is helping you avoid at compile time.
I know this is a late answer but since you are deriving from a pure virtual function for class C, you have to implement it, then in those functions you call the base class:
virtual void foo() const { // for class C
B::foo();
}
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.