Qt/C++ Override function without subclassing - c++

I would like to override a virtual function of a QWidget without subclassing it. It is possible in java. I found this link:
overriding methods without subclassing in Java
Not sure if there is a way in c++ too. Any ideas?

You can't override without inheritance. The code in the linked example does subclass. Perhaps the confusion comes from the fact that it doesn't use the extends keyword. It creates an anonymous subclass of XStream and overrides it's method. Such classes exist in C++ as well and similar code is possible. The naming convention is a bit different. Classes that have no name, but do have a named instance are called unnamed †. Here is my transliteration of the code to show how the example can be done with unnamed class in C++:
class SomeClass {
public:
void myMethod() {
class: public XStream {
protected:
MapperWrapper wrapMapper(const MapperWrapper& next) override {
return MapperWrapper(next); // the example is cut off here, persumably it's creating another nested anonymous class, but i'll keep this simple
}
} xstream;
}
};
You can replace the XStream with QWidget and wrapMapper with one of it's virtual classes if you want to override it in this way.
Anonymous classes are often used for callbacks in Java. But in C++ we have function pointers and lately lambdas, which is probably why the use of unnamed classes is much rarer in C++ code compared to Java. Also, before c++11 unnamed classes were not allowed as template parameters, so they would have been a poor choice for a callback functor.
† In c++, an Anonymous class (or struct) would be one that has no named instance either. It could be a member of another, outer class and the members of the anonymous class would be brought to the namespace of the parent class. Except, anonymous classes are not allowed by the standard. How can there be a definition for such thing then? Well, anonymous unions are allowed and anonymous classes are analoguous to them. Anonymous structs are allowed by C11 standard, though.

Your Java example is a subclass -- it's just an anonymous subclass. The #Override keyword is simply a diagnostic aid: it issues an error if the method doesn't override a superclass. Removing #Override has no effect on the generated code. C++11 has it too -- see this link.
In C++ as in Java, you can't override a virtual function without declaring a subclass. If you want to use Qt effectively, you will have to get used to it!

Related

c++ template class member specialization and inheritance

I would like to write down a set of classes in which there are:
a pure virtual class that wraps an object of any kind and the relate getter for it.
one or more classes for every kind of object I need, extending the virtual one and overriding the getter in order to specialize it.
A template class solution for the wrapper seems to fit the case but I have to use it in two different contexts:
the first one is not aware of wrapper implementations. In this case I should declare a Wrapper<AnyObj> var; with AnyObj standing for any class name (like ? in Java). As far as I know, you can't do this in c++.
the second one is restricted to a particular wrapper implementation. In this case I need the getter to return the wrapped object with the exact type (rather than downcasting it).
If I'm right I cannot use a template class and, moreover, the wrapper won't have a protected: T* wrappedObject member.
I don't know if I'm stuck in the Java approach, wrongly thinking from the beginning, or missing something.
Any suggestion is appreciated.

Without using `protected`, how the subclass can effectively use the variables defined in base class

Bjarne Stroustrup once said that he can address most of the tasks with ONLY private or public member variables and he seldom uses protected member variables in his design. I have heard similar arguments in other places. Here is an example,
class BaseClass
{
...
private:
int m_iAge;
double m_dSalary;
string m_strName;
bool m_bGender;
}
class SubClass : public BaseClass
{
...
}
Given the above class design, how the subclass SubClass can use the variables defined in BaseClass?
Question1> Why we should prefer to having private rather than protected variables? Is it the reason that the BaseClass can hide the implementation detail and make it easy for further improvement?
Question2> In order to let the SubClass access the variable defined in BaseClass, it seems to me that we have to define public access(get/set). However, getter/setter are evil! So the second choice is to define protected access(get/set). Any better idea?
Thank you
Bjarne's point is that generally the derived class shouldn't access the variables of the base class -- doing so frequently leads to maintenance problems. And no, changing it to use get/set (accessor/mutator) functions isn't an improvement.
Ask yourself - why would the derived class ever change the value of m_bGender? Or m_iAge? Doesn't the base class already handle these values correctly?
See, there is generally no need to have direct access to the internals of the base class. So we make them private, and use the class' public interface.
In some very rare cases, there might also be one or two protected functions, if derived classes need some special interface. But that is unusual. If derived classes have different behaviour, we more often use virtual functions for that.
I think the rationale for this claim is that in many situations, subclassing doesn't often change the behavior of the existing (inherited fields), but rather one adds fields and adds new methods that manipulate the new fields.
If you are looking for a way to manipulate inherited members w/o protected, you can, in the base class, make the derived class a friend. You would have to know it ahead of time, though.
The only main reason to use private over protected members is if they indeed are not required in child implementations. That's why we have protected members, because there are cases where the child class does need direct access to members of a parent class. I think Stroustrup is referring to a design whereby there is little need to access parent members in the first place, and child classes simply build upon the functionality of their parent rather than modify the functionality of their parent.
However, getter/setter are evil!
Why so? Getters and setters are an important part of OOP from my experience. There are good reasons to make an interface with a class, rather than access its variables directly.

How can I structure my C++ code so that I only write my common methods once?

If C++.NET allowed multiple inheritance, I would have my common methods in a class and derive from it.
I have classes derived from Panel, Label, TabControl ... which have the same methods exactly.
How can I structure my C++ code so that I only write my common methods once?
Here is a simple example of a property I want to add to each derived class. Extension methods sound ideal, but don't exist in C++.
private: int panelBottomMargin;
public:
[Browsable(true)]
[CategoryAttribute("Layout"), DescriptionAttribute(
"Specify the gap between the last control and the bottom of the panel"),
DefaultValueAttribute(panelBottomMarginDefault)]
[DesignerSerializationVisibility(DesignerSerializationVisibility::Visible)]
property int PanelBottomMargin
{
int get() { return this->panelBottomMargin; }
void set(int margin) { this->panelBottomMargin = margin; }
}
I can't quite make out for sure what you mean by "common methods" here, but generally speaking namespace level non-member functions are the best way to do that (see pretty much every algorithm in the standard library).
If it actually needs access to private attributes of your class then it's probably not a common method and should be implemented in the level of inheritance where the attribute it operates on exist.
It's almost certainly an abuse of inheritance to put common methods into a class that you then inherit from: Use inheritance to extend, NOT to reuse.
Put your common methods in a Utility class, create an instance of this class (pass the object to work on to the constructor) when needed.
What is wrong with static methods? Or instantiating a new class which can operate on objects of the type given? Its best to not abuse inheritance in ways which clearly don't follow the "is-a" doctrine - use "has-a" whenever possible.
Generally, if MI is being considered as a solution to your problem which does not involve "mixin" type semantics, you should consider a new solution.
You could use .NETs "extension methods" if you don't need to access private/protected fields of an object.

Root base class in C++

Every object in .NET inherits (directly or indirectly) from the common root base "Object". Is there such a common object root in C++? How do I pass any object to a function?
public void DoSomeStuff(object o) { ... }
EDIT: To clarify, the purpose: In that function I want to invoke a pointer to member function. For that I need the object instance and pointer to the required function. To simplify readability I want to make a wrapper containing the both required information. I'm not sure if that is the best way, but it is the background idea.
There is no common base class; but using a something like boost::any or more generally a template based approach is preferred over a void*.
There is no common root class. Use either void* to pass any object into a function, or better define some base class.
Template functions are present and avoid the need for such root parent of all classes.
template <class T>
void DoSomeStuff(T const &t) {
// Do the stuff with t...
t.callTheFunction();
}
If all your objects have a member function callTheFunction(), then you got the exactly same behavior than having a root base class, with the same requirement (all your classes have a function with that name).
In addition, you got the additional benefit of being able to specialize the template function DoSomeStuff() for some classes that are not yours, and could not inherit your virtual member function.
For that I need the object instance and pointer to the required function.
That sounds a lot like "delegates". First, you definitely will need to define a common base class for all the objects that you want to call. In C++ you can use multiple inheritance if the object already belong to some other hierarchy.
Then have a read through Member Functions and the Fastest Possible C++ Delegates which is an excellent in-depth article on the topic of delegates (which are an object and member function pointer bound together). Using the header file described in that article, you can create delegates and easily call them just like regular function pointers.
Sorry - there is no root base object in C++. But you can define your own for all your classes.
There is no common base class in C++. However, there are already libraries that allow you to call member functions as delegates. You can try using boost::function together with boost::bind or boost::lambda.
You'd at least depend on a minimum c++ runtime if there were a root object implemented in c++. This is undesirable sometimes.

Is there a way to prevent a method from being overridden in subclasses?

Is anyone aware of a language feature or technique in C++ to prevent a child class from over riding a particular method in the parent class?
class Base {
public:
bool someGuaranteedResult() { return true; }
};
class Child : public Base {
public:
bool someGuaranteedResult() { return false; /* Haha I broke things! */ }
};
Even though it's not virtual, this is still allowed (at least in the Metrowerks compiler I'm using), all you get is a compile time warning about hiding non-virtual inherited function X.
When you can use the final specifier for virtual methods (introduced with C++11), you can do it. Let me quote my favorite doc site:
When used in a virtual function declaration, final specifies that the function may not be overridden by derived classes.
Adapted to your example that'd be like:
class Base {
public:
virtual bool someGuaranteedResult() final { return true; }
};
class Child : public Base {
public:
bool someGuaranteedResult() { return false; /* Haha I broke things! */ }
};
When compiled:
$ g++ test.cc -std=c++11
test.cc:8:10: error: virtual function ‘virtual bool Child::someGuaranteedResult()’
test.cc:3:18: error: overriding final function ‘virtual bool Base::someGuaranteedResult()’
When you are working with a Microsoft compiler, also have a look at the sealed keyword.
A couple of ideas:
Make your function private.
Do not make your function virtual. This doesn't actually prevent the function from being shadowed by another definition though.
Other than that, I'm not aware of a language feature that will lock away your function in such a way which prevents it from being overloaded and still able to be invoked through a pointer/reference to the child class.
Good luck!
Sounds like what you're looking for is the equivalent of the Java language final keyword that prevents a method from being overridden by a subclass.
As others here have suggested, you really can't prevent this. Also, it seems that this is a rather frequently asked question.
(a) I dont think making function private is the solution because that will just hide the base class function from the derived class.The derived class can always define a new function with the same signature.
(b) Making the function non virtual is also not a complete solution because, if the derived class redefines the same function , one can always call the derived class function by compile time binding i.e obj.someFunction() where obj is an instance of the derived class.
I dont think there is a way of doing this.Also,i would like to know the reason for your decision to prohibit derived classes from overriding base class functions.
a compile time warning about hiding non-virtual inherited function X.
change your compiler settings to make it a error instead of warning.
I guess what the compiler warns you about is hiding !! Is it actually being overridden ?
compiler might give you a warning, but at runtime, the parent class method will be called if the pointer is of type parent class, regardless of the actual type of the object it points to.
This is interesting. Try making a small standalone test program for your compiler.
For clarification, most of you misunderstood his question. He is not asking about "overriding" a method, he is asking whether there is a way to prevent "hiding" or not. And the simple answer is that "there is none!".
Here's his example once again
Parent class defines a function:
int foo() { return 1; }
Child class, inheriting the Parent defines the same function AGAIN (not overriding):
int foo() { return 2; }
You can do this on all programming languages. There is nothing to prevent this code from compiling (except a setting on the compiler). The best you'll get is a warning that you are hiding the parent's method. If you call the child class and invoke the foo method, you'll get 2. You have practically broken the code.
This is what he is asking.
If you address the child class as a type of its parent, then a non-virtual function will call the parent class's version.
ie:
Parent* obj = new Child();
Unless you make the method virtual, the child class cannot override it. If you want to keep child classes from calling it, make it private.
So by default C++ does what you want.
Trying to prevent someone from using the same name as your function in a subclass isn't much different than trying to prevent someone from using the same global function name as you have declared in a linked library.
You can only hope that users that mean to use your code, and not others', will be careful with how they reference your code and that they use the right pointer type or use a fully qualified scope.
In your example, no function is overridden. It is instead hidden (it is a kind of degenerated case of overloading).
The error is in the Child class code. As csmba suggested, all you can do is changing your compiler settings (if possible) ; it should be fine as long as you don't use a third party library that hides its own functions.
Technically u can prevent virtual functions to be be overridden. But you will never ever been able to change or add more. That is not help full. Better to use comment in front of function as faq lite suggests.
I was searching for same and yesterday came to this [rather old] question.
Today I found a neat c++11 keyword : final . I thought it may be useful for next readers.
http://en.cppreference.com/w/cpp/language/final
C++ methods are private and un-overridable by default.
You cannot override a private method
You cannot override a non-virtual method
Are you perhaps referring to overloading?