Way To Prevent To Redefine Constructor Definitions - c++

I am writing a custom Exception class, with some additional features over the std::exception one. I added a custom constructor Exception(std::string details) : details(details) {} to my Exception class.
Later, when I extend the Exception class, with the class FileNotAccessibleException, and throw it, I get a compile error saying no matching function for call to ‘FileNotAccessibleException::FileNotAccessibleException(std::basic_string<char>)’ When I then add a method FileNotAccessibleException(std::string details) : Exception(details) {} to my class, it does work fine.
Is there no way to make the constructor work, without having to redefine the constructor for all my classes?

You can inherit the constructors of the base class with a using declaration:
class FileNotAccessibleException : public Exception
{
public:
using Exception::Exception;
...
};
See more on inherited constructors on Bjarne Stroustrup's C++11 FAQ.
Note: this does not apply to pre-C++11 implementations, and was one of the last C++11 language features to be added to popular compilers such as G++ and CLANG.

Related

Why does std::logic_error not virtually inherit from std::exception?

I'm trying to implement a custom exception hierarchy and allow appropriate std::* to be caught by code.
class my_exception : public virtual std::exception {
};
class my_bad_widget_state : public virtual my_exception, public virtual std::logic_error {
public: my_bad_widget_state() : std::logic_error("widget oops") {}
};
Obviously my_bad_widget_state is a my_exception and is also a std::logic_error, but the compiler rejects this code because std::exception doesn't say virtual when inheriting exception so there's an ambiguity. The compiler is right, but I think the standard library might be wrong, or?
edit:
Obviously my_bad_widget_state is a my_exception so a logic_error and also a std::exception, and when my_bad_widget_state is thrown std::exception is not being caught.
edit:
I am interested in knowing whether the standard library is designed this way for a particular reason that I failed to understand so far (if so, what is that reason please) or is it some kind of an oversight. My research indicates that many people seem to think this is a problem, but I didn't find any reason the inheritance shouldn't be virtual.
Q1: why is the inheritance in the standard library not virtual?
Q2: how can this be implemented correctly? [answered]
[W]hy is the inheritance [w.r.t. exceptions] in the standard library not virtual?
Simply, multiple inheritance, in the standard exception hierarchy, wasn't intended to be supported. It is not virtually derived, and this is, in effect, what it means.
By contrast, where in the standard library is this supported? I/O streams is the first example that comes to mind. In particular the use of basic_ios all the way down the hierarchy to basic_iostream. In this case, it was intended that the base was virtually derived to support the multiple inheritance and that the "diamond problem" was avoided.
So why is this, how should std::exception be used?
std::exception has multiple exceptions that are derived from it, in particular, note the std::logic_error and std::runtime_error. The standard library has already given us a board pattern for classification and organisation of our exceptions, namely;
class logic_error;
Defines a type of object to be thrown as exception. It reports errors that are a consequence of faulty logic within the program such as violating logical preconditions or class invariants and may be preventable.
And
class runtime_error;
Defines a type of object to be thrown as exception. It reports errors that are due to events beyond the scope of the program and can not be easily predicted.
Of course these are not the only two, but they capture and are a base of a significant number of other standard library exceptions.
Where to root the exception hierarchy?
If you wish to use the standard library exception hierarchy, it is better to choose a point at which to extend the hierarchy and work from that point on. Hence, if there is a desire to have a custom root exception, then have std::exception as a base class and derive further custom exceptions from that custom base onwards.
If the custom exceptions are divisible between runtime and logic errors, then derive the custom exception hierarchy from that level onwards.
Using a custom exception hierarchy rooted somewhere in the standard library exceptions is generally a good idea. At what point that root(s) should be is dependent on the actual intended use of the code. See here for a broader Q&A on this.
What about boost exceptions?
Boost uses virtual inheritance, they do this to exactly support the multiple inheritance that the standard library does not support. It also supports some additional features not found in the standard library.
That said, boost still uses the std::exception as a base class.
Ultimately this becomes a design decision based on the inheritance structures you wish to support in the hierarchy.
std::logic_error cannot be inherited without declaring a constructor. If you are using C++11, you can inherit the base class constructor by utilizing using:
class MyException : public std::logic_error {
public:
using std::logic_error::logic_error;
};
In C++0x, you just have to explicitly write a constructor that takes an std::string and forwards it to the base-class constructor like so:
class MyException : public std::logic_error {
public:
MyException(std::string const& msg) : std::logic_error(msg) { }
};
Virtual inheritance is rather awkward to use in a concrete hierarchy, because you need to initialize a virtual base in all descendant classes (children, grandchildren, ...)
If you want to add functionality to all standard exception classes, you can do this
class my_exception_additions {
// no inheritance from std::exception
};
template <class E>
class my_exception : public E,
public my_exception_additions {
...
};
...
throw my_exception<std::logic_error>("oops");
Of course the template will need to forward constructors to E.
Now if you want two separate hierarchies, like std::exception and your sql_exception from the comments, the template machinery becomes too complicated and it's better to resort to manually defining all classes:
class abstract_sql_exception {...};
class sql_exception : public abstract_sql_exception,
public std::exception {...};
class abstract_sql_disconnected : public abstract_sql_exception {...};
class sql_disconnected : public abstract_sql_disconnected,
public std::runtime_error {...};
class abstract_sql_invalid_input : public abstract_sql_exception {...};
class sql_invalid_input : public abstract_sql_invalid_input,
public std::logic_error {...};
Here, the abstract_sql hierarchy exists completely independently from the std:: hierarchy. Only concrete leaf classes tie the two together.
I must say that this is a (more or less ugly) workaround, not an ideal solution. The standard should have probably specified virtual inheritance throughout the exception hierarchy.
std::logic_error doesn't inherit virtually from std::exception because the standard doesn't say it does. The reason for that is likely that it is largely unneeded to express how the standard uses exceptions. Virtual inheritance also adds complexity and cost (albeit insignificant compared to exception handling)
You can certainly do what you want by not inheriting virtually with the caveat that you'd have two base std::exception objects in my_bad_widget_state. The primary issue with that is that you then can't catch a my_bad_widget_state exception by catch (std::exception& e) ... because the conversion to std::exception is ambiguous.
My advice is to not to use virtual inheritance and instead either stick to the exception classes (logic_error, runtime_error, etc.) or have all your exceptions inherit exclusively from my_exception. If you are pursuing this model because of shared functionality in my_exception, you'd probably opt for the latter.

Why can't we define an anonymous class in place for inheritance?

class MyClass : SomeFeatureGeneratedByTemplate<MyClass>
Template offers much convenience to add a feature to our class just by inheriting a instantiated class template.
However, sometimes the feature may get too complicated to be implemented by template, where macro might be the only choice.
MACRO_TO_GENERATE_COMPLICATED_FEATURE(MyClass)
/* Might be expanded to
#ifndef MYCLASS_FEATURE_CLASS
#define MYCLASS_FEATURE_CLASS
class MyClassFeature { ... };
#endif
*/
class MyClass : MyClassFeature
I wonder if the following syntax would simplify this:
allow to define a anonymous class just in place
class MyClass : class { ... }, class{ ... }
Therefore, the above code could be rewritten as:
class MyClass : MACRO_GEN_FEATURE(MyClass)
APPEND:
Q: Why don't I embed the code just inside class?
A:
1. This feature should be explicit and exposed to user. When they generating docs, derived class is easy to discover :class A: FEATURE1(A), FEATURE2(A) while embedded macro isn't. Although an empty class could be derived to achieve our goal(e.g class A: FEATURE1(A)//just derive predefined struct FEATURE1_EMPTY{};), apparently it is not a perfect solution.
Sometimes we even needn't to get any member from the class generated by macro, but that class has to include member to provide some function(e.g static_assert with some helper class templates).
Complete specialization of a nested class template is not allowed, which prevents me from using nested class to avoid namespace conflicts mentioned in 2).
I know that this is illegal right now, but why is this not allowed in C++ standard?
Because neither Bjarne (in the 1980s) nor anybody on the ISO committee (1990s—now) saw a need for this. I've never seen a need for it until this macro hackery today.
Here's how a language is developed:
Start with nothing
Feature is needed? Add it!
Here's how a language is not developed:
Start with every possible feature, in an ∞-pages long standard
Feature not needed? Remove it!
class MyClass : class { /* CONTENT */ } {
// HERE
};
What ever you would put where CONTENT is, would be only used or even accessible from the class MyClass, so it can equally well be written where the HERE stands.
If you want to "organise" the contents of a single class, you could use "nested" classes to enhance encapsulation:
class Thing {
class SomeSubThing {} subthing;
};
Though whether this useful or even recommendable is highly depended of the actual case and probably highly subjective.

Qt/C++ Override function without subclassing

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!

Strange "type class::method() : stuff " syntax C++

While reading some stuff on the pImpl idiom I found something like this:
MyClass::MyClass() : pimpl_( new MyClassImp() )
First: What does it mean?
Second: What is the syntax?
Sorry for being such a noob.
This defines the constructor for MyClass.
The syntax is that of a constructor definition with an initialization list (I assume there is a set of braces following this that define the body of the constructor).
The member pimpl_ of MyClass is being initialized as a pointer to a new object of type MyClassImp. It's almost the same as the following:
MyClass::MyClass()
{
pimpl_ = new MyClassImp();
}
However, it is preferable to use the initialization list for initializing class members wherever possible; see the C++ FAQ Lite entry linked above.
It's an initialization list.
It allow you to set the values of member and base class constructor before the constructor code is called.
You should use it to initialize the values of your class instance.
In addition to being a constructor with an initialiser list as others have already explained, it's also using the private implementation pattern.
C++ requires the class declaration to include all the public and private members of the class. This can result in you having to expose implementation details that you don't want to, and to making your implementation part of your API/ABI. It can also significantly increase compile times due to additional #includes in the public headers to support the private member variables.
Making a second class with the actual implementation and just exposing the functional API makes this much cleaner, but at the cost of an additional layer of indirection.
C generally handles this by having a pointer to an opaque object which the library creates and destroys for you.

Is it possible to forbid deriving from a class at compile time?

I have a value class according to the description in "C++ Coding Standards", Item 32. In short, that means it provides value semantics and does not have any virtual methods.
I don't want a class to derive from this class. Beside others, one reason is that it has a public nonvirtual destructor. But a base class should have a destructor that is public and virtual or protected and nonvirtual.
I don't know a possibility to write the value class, such that it is not possible to derive from it. I want to forbid it at compile time. Is there perhaps any known idiom to do that? If not, perhaps there are some new possibilities in the upcoming C++0x? Or are there good reasons that there is no such possibility?
Bjarne Stroustrup has written about this here.
The relevant bit from the link:
Can I stop people deriving from my class?
Yes, but why do you want to? There are two common answers:
for efficiency: to avoid my function
calls being virtual.
for safety: to ensure that my class is not used as a
base class (for example, to be sure
that I can copy objects without fear
of slicing)
In my experience, the efficiency reason is usually misplaced fear. In C++, virtual function calls are so fast that their real-world use for a class designed with virtual functions does not to produce measurable run-time overheads compared to alternative solutions using ordinary function calls. Note that the virtual function call mechanism is typically used only when calling through a pointer or a reference. When calling a function directly for a named object, the virtual function class overhead is easily optimized away.
If there is a genuine need for "capping" a class hierarchy to avoid virtual function calls, one might ask why those functions are virtual in the first place. I have seen examples where performance-critical functions had been made virtual for no good reason, just because "that's the way we usually do it".
The other variant of this problem, how to prevent derivation for logical reasons, has a solution. Unfortunately, that solution is not pretty. It relies on the fact that the most derived class in a hierarchy must construct a virtual base. For example:
class Usable;
class Usable_lock {
friend class Usable;
private:
Usable_lock() {}
Usable_lock(const Usable_lock&) {}
};
class Usable : public virtual Usable_lock {
// ...
public:
Usable();
Usable(char*);
// ...
};
Usable a;
class DD : public Usable { };
DD dd; // error: DD::DD() cannot access
// Usable_lock::Usable_lock(): private member
(from D&E sec 11.4.3).
If you are willing to only allow the class to be created by a factory method you can have a private constructor.
class underivable {
underivable() { }
underivable(const underivable&); // not implemented
underivable& operator=(const underivable&); // not implemented
public:
static underivable create() { return underivable(); }
};
Even if the question is not marked for C++11, for people who get here it should be mentioned that C++11 supports new contextual identifier final. See wiki page
Take a good look here.
It's really cool but it's a hack.
Wonder for yourself why stdlib doesn't do this with it's own containers.
Well, i had a similar problem. This is posted here on SO. The problem was other way around; i.e. only allow those classes to be derived that you permit. Check if it solves your problem.
This is done at compile-time.
I would generally achieve this as follows:
// This class is *not* suitable for use as a base class
The comment goes in the header and/or in the documentation. If clients of your class don't follow the instructions on the packet, then in C++ they can expect undefined behavior. Deriving without permission is just a special case of this. They should use composition instead.
Btw, this is slightly misleading: "a base class should have a destructor that is public and virtual or protected and nonvirtual".
That's true for classes which are to be used as bases for runtime polymorphism. But it's not necessary if derived classes are never going to be referenced via pointers to the base class type. It might be reasonable to have a value type which is used only for static polymorphism, for instance with simulated dynamic binding. The confusion is that inheritance can be used for different purposes in C++, requiring different support from the base class. It means that although you don't want dynamic polymorphism with your class, it might nevertheless be fine to create derived classes provided they're used correctly.
This solution doesn't work, but I leave it as an example of what not to do.
I haven't used C++ for a while now, but as far as I remember, you get what you want by making destructor private.
UPDATE:
On Visual Studio 2005 you'll get either a warning or an error. Check up the following code:
class A
{
public:
A(){}
private:
~A(){}
};
class B : A
{
};
Now,
B b;
will produce an error "error C2248: 'A::~A' : cannot access private member declared in class 'A'"
while
B *b = new B();
will produce warning "warning C4624: 'B' : destructor could not be generated because a base class destructor is inaccessible".
It looks like a half-solutiom, BUT as orsogufo pointed, doing so makes class A unusable. Leaving answers