This question already has answers here:
Is there a way to prevent a method from being overridden in subclasses?
(14 answers)
Closed 7 years ago.
The situation is like this.
class Interface
{
public:
virtual void foo() = 0;
}
class MyClass : Interface
{
public:
virtual void bar() = 0;
private:
void foo()
{
//Some private work and checks.
bar();
};
}
I want that my user will create a class which inherit from MyClass, and they will have to implement there bar().
But how can I enfoce they wouldn't override foo()? because it's important to me to use my foo().
In C++11 you can mark the method as final to prevent it from being overriden:
class MyClass : Interface
{
public:
virtual void bar() = 0;
private:
void foo() final
{
//Some private work and checks.
bar();
};
}
As per other answer, you can use final keyword in C++11 (such facility is similar to Java's final keyword).
For C++03 code, you can use CRTP mechanism (provided if you can change the definition of Interface)
template<typename Derived>
class Interface
{
public:
void foo() // not 'virtual'
{
static_cast<Derived*>(this)->foo();
}
}
class MyClass : public Interface<MyClass>
{
public:
virtual void bar() = 0;
private:
void foo()
{
//Some private work and checks.
bar();
};
}
So now you have remove the virtualness of the foo() and the binding will happen at compile time. Remember that CRTP comes with its own limitation, so whether to use it or not is up to you.
Related
This question already has answers here:
C++ multiple inheritance function call ambiguity
(3 answers)
Closed 3 years ago.
I am inheriting from two classes. Both classes contain the same function name, but one being implemented and one being pure virtual. Is there any way that I can just use the one already implement?
#include <iostream>
using namespace std;
class BaseA {
public:
void DoSomething() {
value += 1;
std::cout<<"DoSomething():"<< value<<endl;
}
int value;
};
class BaseB {
public:
virtual void DoSomething() =0;
};
class Derived : public BaseA, public BaseB {
public:
Derived() { value = 0; }
// Compiler complains DoSomething() is not implemented.
// Can we just use BaseA.DoSomething()?
};
int main() {
Derived* obj = new Derived();
obj->DoSomething();
}
You need to define a function because DoSomething is a pure-virtual function in BaseB class. But you can call the DoSomething from BaseA class in your implementation:
void DoSomething(){
BaseA::DoSomething();
}
So assume there is class A with function foo.
Class A is the parent of a few classes which all have the function foo.
All of the child classes need the functionality of
A::foo and adds upon it.
For example:
class A
{
public:
void foo()
{
print('A');
}
};
class B:public A
{
public:
void foo()
{
print("B");
}
};
class C:public A
{
public:
void foo()
{
print("C");
}
};
void main()
{
B b;
C c;
c.foo()// now only goes to C::foo(), meaning print C. I want it to to also go into A::foo() meaning print AC
b.foo()//now only goes to B::foo(),meaning print B. want it to print AB
}
And if I want to add class D : A with foo function it will also do A::foo() and then D::foo()
Sorry if I am missing something obvious.
EDIT : since it wasn't clear the question was if there is an automatic way to do so.
EDIT : found a workaround:
class A
{
virtual void foo2(){}
public:
void foo()
{
print('A');
foo2();
}
};
class B:public A
{
void foo2()
{
print("B");
}
public:
};
class C:public A
{
void foo2()
{
print("C");
}
public:
};
void main()
{
B b;
C c;
c.foo()// now prints AC
b.foo()//now prints AB
}
seems redundant since now there are 2 functions now.
You can call the parent class's implementation of a function using A::foo().
In your case, simply adding that function call will achieve the result you want:
class B:public A
{
public:
void foo()
{
A::foo();
print("B");
}
};
As a side note, whenever you intend to override functions, you should declare it as virtual:
class A
{
public:
virtual void foo()
{
print('A');
}
};
And then when overriding it, use the override keyword:
class B:public A
{
public:
void foo() override
{
print("B");
}
};
What you've called a workaround is an established solution to this question, and whilst some people might call it a workaround many wouldn't.
Its even got a name that covers it. The non-virtual interface pattern.
herb sutter :- http://www.gotw.ca/publications/mill18.htm
One example from S.O., there's probably more:-
Non-virtual interface design pattern in C#/C++
I'd argue that this IS a way to do it automatically.
As to your aside that its redundant because there are 2 functions - well there were 2 before (the base version and derived version).
One benefit of this approach in some designs is that if the virtual method foo2 is pure virtual (which would make A abstract) then this forces all immediate derived classes to implement foo2. (I say immediate because if B derives from A it must implement foo2 but if C then derives from B C isn't forced to implement foo2, it has access to B::foo2 )
The code scenario is as follows:
class ParentClass {
void foo();
virtual void doSomething() { foo(); }
};
class ChildClass : public ParentClass {
virtual void doSomething();
};
Now, is there a way to force the child class to call the parent class' doSomething()? Let's assume that calling foo() is vital and should always be called when doSomething() is called. The child class can of course call ParentClass::doSomething(), but it seems a bit "risky" as it is not enforced.
I have come up with a "dirty" solution which is something like this:
class ParentClass {
void foo();
void doSomething() final {foo(); doSomethingChild(); }
virtual void doSomethingChild() = 0;
};
class ChildClass : public ParentClass {
virtual void doSomethingChild();
};
This way, child classes have to do the implementation and foo() is always called, but the method is not the same anymore. Is there any solutions that are more elegant?
This is not a dirty solution, but the non-virtual interface idiom (or template method pattern) that you discovered by yourself.
By defining a non-virtual function that calls a virtual function (among other things), you force every implementation of your class to implement the behavior of the non-virtual. The implementation are only free to modify part of this behavior, that is, the call to the virtual function.
This is usually done like so:
class Base {
public:
void foo() {
//do stuff
fooImpl();
//do other stuff
}
private:
virtual void fooImpl(); //pure or not
};
class Derived : public Base {
private:
virtual void fooImpl(){
// Implement or change fooImpl behavior
}
};
Making the non virtual public and the virtual private ensures as well that nobody can call fooImpl on these classes, which is what you want as you need some stuff to be perfom before and/or after the call to fooImpl.
Let see could this work :
class parent {
void foo() {...}
virtual void doFinal() {...}
void doSomething (){foo(); doFinal();}
}
class child {
virtual void doFinal() {...}
}
So you can reimplement doFinal ans use doSmthing.
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.,
This question already has answers here:
Is there a way to prevent a method from being overridden in subclasses?
(14 answers)
Closed 7 years ago.
How can I enforce that a base class method is not being overridden by a derived class?
If you are able to use the final specifier from C++11 you can prevent derived classes from override that method. (Microsoft compilers appear to support the similar sealed with similar semantics.)
Here's an example:
#include <iostream>
struct base {
// To derived class' developers: Thou shalt not override this method
virtual void work() final {
pre_work();
do_work();
post_work();
}
virtual void pre_work() {};
virtual void do_work() = 0;
virtual void post_work() {};
};
struct derived : public base {
// this should trigger an error:
void work() {
std::cout << "doing derived work\n";
}
void do_work() {
std::cout << "doing something really very important\n";
}
};
int main() {
derived d;
d.work();
base& b = d;
b.work();
}
Here's what I get when I try to compile it:
$ g++ test.cc -std=c++11
test.cc:17:14: error: virtual function ‘virtual void derived::work()’
test.cc:5:22: error: overriding final function ‘virtual void base::work()’
If you make the method non-virtual, derived classes cannot override the method. However, in C++03 a class cannot override a method from a base class, and also prevent further derived classes from overriding the same method. Once the method is virtual, it stays virtual.
Don't make it virtual.
This won't prevent deriving from your class and hiding the function (by providing another member function with the same name). However, if your class is not meant to be derived anyway (no virtual destructor, no virtual member functions), that shouldn't be an issue.
well if you want to keep it public, dont declare it virtual.
EDIT: Srikanth commented wondering about overriding a private member function in a derived class.
class A
{
public:
virtual ~A(){};
void test()
{
foo();
};
private:
virtual void foo()
{
std::cout << "A";
};
};
class B : public A
{
public:
virtual void foo()
{
std::cout << "B";
};
};
void test()
{
B b;
A& a = b;
a.test(); // this calls the derived B::foo()
return 0;
}`
well as far as i know you can't do that on c++, you can try to declare it as private. . find more info on this link http://en.allexperts.com/q/C-1040/prevent-overriding-functions-derived.htm
Short answer: there is no need for that. Long answer you can do some twists, but is it worth it?