First of all I'm sorry if this is asked already but I couldn't find answer.
So, can I have class A and it inherits class B, can I access class A function from class B?
This is just example.
class A : public B
{
void aFoo() { cout << "A" << endl; }
};
class B
{
void bFoo() { aFoo(); }
};
So, is this possible in any way and if it is how it can be done?
You could use a virtual function in B and reimplement it in A, however you still have to create the object as A, for example:
class A : public B {
void aFoo() { cout << "A" << endl; }
};
class B {
void bFoo() { aFoo(); }
virtual void aFoo() { cout << "B" << endl; } //or
virtual void aFoo() = 0; // turning B into an abstract class.
};
.......
B* ab = new A;
Yes (with templates)... You can use the Parent class as a template class which receieves the the Type of its child, so it can cast itself to that type... e.g.:
template <typename T>
class A
{
public:
A() = default;
void afoo()
{
reinterpret_cast<T*>(this)->bfoo();
}
};
class B : public A<B>
{
public:
B() = default;
void bfoo()
{
std::cout << "In B::bfoo()";
};
};
int main()
{
B b;
b.afoo();
}
This way you can avoid virtual inheritance.
No. Derived classes can access base class members and methods if declared public/protected. It does not work the other way round.
So, is this possible in any way and if it is how it can be done?
No. You can't. Note that inheritance doesn't work in reverse. The base class and its objects don’t know anything about any classes derived from the base class.
If your question is about whether it is possible syntactically, then as others have answered - No you can't because that's not how it works.
However, if you are looking for a design pattern to solve an issue in which this is something you would like to have, then I think what you are looking for is a Bridge Pattern where the parent class calls a virtual function which is implemented differently in each different child class (exactly what OneofOne answered).
More about the Bridge Pattern: http://sourcemaking.com/design_patterns/bridge/cpp/1
Related
This is the code I got from the internet...
and how virtual keyword is working?
i think this virtual keyword has something to do with this behaviour but I don't understand what it is.
class A {
int x;
public:
A(int i) { x = i; }
void print() { cout << x; }
};
class B : virtual public A {
public:
B()
: A(10)
{
}
};
class C : virtual public A {
public:
C()
: A(10)
{
}
};
class D : public B, public C {
};
int main()
{
D d;
d.print();
return 0;
}
why am I able to call grandparent method with grandchild object?
Because that is how inheritance works. That member function was inherited by the child class and the grand child.
I read that it was not possible
Either what you read is wrong or you misunderstood it.
how virtual keyword is working?
When a virtual base occurs multiple times in a hierarchy, those occurrences are combined into a single base sub object.
In the case of D, the base A of B and the base A of C are the same base which would not be the case if the inheritance wasn't virtual.
You can be right in your assumption, but it is not that easy.
print is declared as a public member function. Since you derive every class with public, you still can call print from your D class object.
If you desire your described behaviour, one way is, you have to rewrite your class
class A {
int x;
public:
A(int i) { x = i; }
private:
void print() { cout << x; }
};
You should study the topic of 'inheritance'. You can start with that ARTICLE.
In general a diamond class structure points to bad software design. Yeah there may be some good reasons to create something like that. But judging the type of the question, you should really forget about that and avoid it. Unless you are really sure about what you are doing.
The structure you found is described here.
I give the following example to illustrate my question:
class Base
{
public:
virtual void do()=0;
}
class A: public Base
{
public:
void do();
};
class B: public Base
{
public:
void do();
}
class AB: public Base
{
public:
void do()
{
a_.do();
// if not succeed
{
b_.do();
}
}
private:
A a_;
B b_;
}
From the above codes, we can see that class A, B and AB come from the same Base class. class AB, however, needs to invoke both class A and class B. Here is my question: what's the potential problem with the class AB? Are there other alternatives?
One alternative might be:
class Base
{
public:
virtual void do()=0;
}
class A: public Base
{
public:
void do();
};
class B: public Base
{
public:
void do();
}
class AB: public A
{
public:
void do()
{
A::do();
// if not succeed
{
b_.do();
}
}
private:
B b_;
}
I have no idea what you really want to achieve. But if all of your classes should only have one copy of instance data from Base, you need a virtual Base class.
The problem from your first example with AB is, that you have three! times data of class Base. One from inherit Base, one as part of Member B which itself derives from Base and the same from Member A. Is that what you intend?
I give you the following snipped to see how you can work with exact ONE copy of Base in all of your class instances. Maybe that is what you want to get?
I add some data to Base to see how construction works while using virtual base classes. It is important that the base class constructor will not be called from the constructors of directly inherited classes! You need to call the constructor directly from the outermost constructor as shown in class AB constructor!
As a remark: Virtual Base classes should be used only if nothing else fits the design. Often the need of such a solutions shows a design problem. But as always in programming: If this fits exactly your needs, it is technically absolutely ok to do it.
class Base
{
private:
std::string text;
public:
Base( const std::string& str ): text(str) {}
virtual void Do() { std::cout << text << std::endl; }
};
class A: virtual public Base
{
public:
A():Base("Default from A") {}
void FuncA() { std::cout << "FuncA" << std::endl; }
void Do() { std::cout << "Via A" << std::endl; Base::Do();}
};
class B: virtual public Base
{
public:
B(): Base ("Default from B") {}
void FuncB() { std::cout << "FuncB" << std::endl; }
};
class AB: public A,B
{
public:
//Important to know that init of Base MUST be done from here and not from A nor B !!
AB( const std::string &s): Base(s) {}
void Do() { std::cout << "Via AB" << std::endl; Base::Do(); A::Do(); B::Do();}
};
int main()
{
A a;
a.Do();
std::cout << "####" << std::endl;
B b;
b.Do();
std::cout << "####" << std::endl;
AB ab("Hallo");
ab.Do();
std::cout << "####" << std::endl;
}
what's the potential problem with the class AB?
I don't know of any well known problem that would necessarily arise from your design. You should ask yourself "Why would there be a problem?".
Are there other alternatives?
There are many alternatives. For example, neither A nor B contain any state, so you could just as well stop using classes in favor of free functions and replace dynamic binding with a function pointer.
To be able to compare different alternatives, you should first decide what problem you are trying to solve.
You should inherit from A and B and not from Base, because A and B already do so.
Consider the following example:
class A{
public: virtual void hello() = 0;
};
class B: public A{};
class C {
public: void hello(){
cout<<"Hi";
}
};
class D: public B, public C{};
The idea is that I would like to inject the implementation of hello into D through C. This doesn't seem to work unless I make C inherit from A too. Since that leads to diamond inheritance, I end up using virtual inheritance.
Is there any alternative to forcing an implementation into a derived class, without disturbing the abstract classes A and B here?
EDIT: I want a solution where I don't need to explicitly write code within D. This is because, I have many classes like D having the same implementation, which is exactly why I would like to push that implementation up to some class from which all of them inherit.
You can rewrite C as a template class that inherits from it's template argument and then derive D from C.
template <class Base>
class C : public Base {
public: void hello(){
cout<<"Hi";
}
};
class D: public C<B> {};
You can consider static inheritance/ policy classes when you need to inject an outside method into a class hierarchy. Note that injecting the method usually means that the method does not have the same name as an existing virtual in the class hierarchy (if it does, you are forced to use virtual inheritance or explicitly call with the scope :: or insert it in the class hierarchy). I called the method externalHello here.
The other options work fine as well but they conceptually point more to the fact that the injected method is not really an abstract method that could be used outside of this class hierarchy but should have been part of it in the first place.
class A
{
public:
virtual void hello() = 0;
};
class B: public A
{
public:
void hello()
{
cout<<"Hi from B" << endl;
};
};
template<typename T> class C1
{
public:
void injectedMethodUnrelatedToClassHierarchy()
{
cout<<"Hi from C1 with unrelated method" << endl;
};
void externalHello()
{
static_cast<T*>(this)->hello(); // will still call hello in B
injectedMethodUnrelatedToClassHierarchy(); // this will call hello here
};
};
class D: public B, public C1<D>{};
With client code:
D dx;
dx.hello();
dx.externalHello();
dx.injectedMethodUnrelatedToClassHierarchy();
It may work
#include<iostream>
using namespace std;
class A
{
public:
virtual void hello() = 0;
};
class C {
public: void hello(){
cout<<"Hi\n";
}
};
template<typename T>
class B: public A, public T
{
public:
void hello() override{ //override A::hello()
//do other staff
T::hello(); // call C::hello()
}
};
class D: public B<C>{
};
int main()
{
D d;
d.hello();
return 0;
}
I have a diamond design currently, and I saw a related question here
In that question, let me assume that class B and class C are virtual inherited from Class A, so in Class D, when we need to call virtual functions, we need to specify which one needed to call.
D::foo()
{
B::foo(); //specify foo() in B
}
For my diamond design, I have a lot of virtual functions to rewrite, in order to let these functions called by correct B or C father class functions.
It is not good, a lot of repeated work need to be done, when I have child class, do you have some better solutions, so that I can call foo() of B in class D but no rewrite for the example above.
Since C++11, you can do an aliasing:
class A
{
public:
virtual void foo() { cout << "A" << endl; }
}
class B : public virtual A
{
public:
void foo() { cout << "B" << endl; }
}
class C : public virtual A
{
public:
void foo() { cout << "C" << endl; }
}
class D : public B, C
{
using B::foo;
}
This way, doin:
D obj;
obj.foo();
Will output B;
I think template classes might do the trick here.
http://www.cplusplus.com/doc/tutorial/templates/
Coluld you provide a simple code example? (sorry C++ nube) and how to call a function from the class you are extending?
A bit useful example: :-)
class CImplementation
{
public:
void doFoo();
};
void CImplementation::doFoo()
{
//implementation
}
class IInterface
{
public:
virtual void foo()=0;
};
class DerivedFromImplementationAndInterface : public CImplementation, public IInterface
{
virtual void foo();
};
void DerivedFromImplementationAndInterface::foo()
{
doFoo();
}
//possible usage:
void method(IInterface& aInterface)
{
aInterface.foo();
}
void test()
{
IInterface* d = new DerivedFromImplementationAndInterface;
method(*d);
}
In C++, you can extend multiple classes, it's called multiple inheritance. Most probably this is what you're looking for. Please read a good book about multiple inheritance and C++ (a quick introduction: http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr134.htm), because there are many pitfalls and details to pay attention to.
Example for multiple inheritance:
class A { ... };
class B { ... };
class C: public A, public B {}; // C inherits from A and B.
C++ doesn't explicitly have interfaces, the equivalent of an interface in Java is usually implemented with a class having only pure virtual functions (plus constructors, destructor, copy assignment):
#include <iostream>
// interface
class Fooable {
public:
virtual int foo() = 0;
virtual ~Fooable() {}
};
// base class
class Base {
public:
void non_virtual_function() { std::cout << "Base::non_virtual_function\n"; }
virtual void virtual_function() { std::cout << "Base::virtual_function\n"; }
};
// derived class, inherits from both Base "class" and Fooable "interface"
class Derived: public Base, public Fooable {
public:
virtual int foo() {
// call base class function
Base::non_virtual_function();
// virtual call to function defined in base class, overridden here
virtual_function();
}
virtual void virtual_function() {
// call base class implementation of virtual function directly (rare)
Base::virtual_function();
std::cout << "Derived::virtual_function\n";
}
void non_virtual_function() {
// not called
std::cout << "Derived::non_virtual_function\n";
}
};
int main() {
Derived d;
d.foo();
}
Not sure what you're asking:
class A
{
public:
void method();
};
class B
{
public:
void method();
};
class C : public A, public B
{
public:
void callingMethod();
};
void C::callingMethod()
{
// Here you can just call A::method() or B::method() directly.
A::method();
B::method();
}
Note that multiple inheritance can lead to really hard-to-solve problems and I would recommend to only use it when necessary.
The question as stated,
C++ is it possible to make a class extend one class and implement another?
does not make much sense. The answer to that is just "yes". You can derive from any number of classes: C++ fully support multiple inheritance.
So, given that the question as stated isn't really meaningful, it's at least possible that you meant to ask
C++ is it possible to make a class extend one class and thereby implement another?
The answer to this question is also yes, but it's not trivial. It involves virtual inheritance. Which is quite tricky.
Here's an example:
#include <iostream>
void say( char const s[] ) { std::cout << s << std::endl; }
class TalkerInterface
{
public:
virtual void saySomething() const = 0;
};
class TalkerImpl
: public virtual TalkerInterface
{
public:
void saySomething() const
{
say( "TalkerImpl!" );
}
};
class MyAbstractClass
: public virtual TalkerInterface
{
public:
void foo() const { saySomething(); }
};
class MyClass
: public MyAbstractClass
, public TalkerImpl
{};
int main()
{
MyClass().foo();
}
The virtual inheritance ensures that there is only one sub-object of type TalkerInterface in a MyClass instance. This has some counter-intuitive consequences. One is that "inheriting in an implementation" works, and another is that construction of that base class sub-object happens down in each MyClass constructor, and more generally down in the most derived class.
Cheers & hth.,