The following code is from here:
#include <streambuf> // for std::streambuf
#include <ostream> // for std::ostream
class fdoutbuf
: public std::streambuf
{
public:
explicit fdoutbuf( int fd );
//...
};
class fdostream
: public std::ostream
{
protected:
fdoutbuf buf;
public:
explicit fdostream( int fd )
: buf( fd ), std::ostream( &buf ) // This is not allowed.
// buf can't be initialized before std::ostream.
{}
//...
};
I didn't really understand the comment. Why "buf can't be initialized before std::ostream"? Can I use some help understanding this?
The order of initialization is determined by the order of declaring your class members, and inherited classes come before all of that. Take a simple example that illustrate the basic problem without referring to inheritance :
class C
{
int a, b;
public:
C() : b(1), a(b) {} // a is initialized before b!
};
The code doesn't do what you think! a is initialized first, then b is initialized to one. So it depends on the order of the declaration not the order in the initialization list:
int a, b;
Now, the same idea applies to base classes which are initialized before the derived class members. To solve this problem, you create a class that you inherent which contains the member you want to initialize from a base class. Of course, that helper class must come before the one you are actually deriving from.
You have to call the base class constructor before you initialize your member variables, but you pass a pointer to buf (a member variable which is undefined at this point) to this constructor.
Related
I was happy to find out that in C++11 we can inherit constructors like:
class Foo
{public:
Foo(int a, double b, std::string name, char somethingElse);
};
class Derived : public Foo
{public:
using Foo::Foo;
};
But I'm finding that I'm often extending the base class where there might be maybe one or two extra features, and I need to initialise a couple extra members by maybe passing as extra argument or something. In this case is seems I have to rewrite the constructor and pass all the arguments to the base one. I'm wondering if there is a better solution. I thought maybe just using the inherited constructor and then initialising the extra member on the next line after construction, but it doesn't seem right:
Derived d = Derived(6, 6.0, "name", 'a');
d.extraMember = 4;
d.funcptr = &somefunction;
I figured it was an excellent feature but then I realised more and more that my extended classes needed extra initialisation info.
Here's my example from my code:
struct Window
{
Window(Window* parent, vec2 position, vec2 size, const String& name);
};
struct ConsoleWindow : Window
{
using Window::Window;
// But I've had to rewrite the constructor again because in this constructor I do stuff like
//GUI::bIsConsoleWindowActive = true;
//GUI::unselectWindow();
//GUI::selectedWindow = this;
}
It seems to me you can't add extra things to the construction process without rewriting the constructor and calling the base and passing all the values. This is common throughout my classes.
If your base classes are copyable/moveable and not abstract, you can push the burden of constructing the base class onto the declaration of the derived object. Just accept a base object:
Derived(Base b, int extraMember) :
Base(std::move(b)), extraMember(extraMember)
{
}
Where the declaration becomes this
Derived d{Base{6, 6.0, "name", 'a'}, 4};
That isn't perfect either, since it places certain requirements on your base classes that may not hold. And if it looks like aggregate initialization to you, then that's because this sets out to mimic it.
I'm afraid the only way that can definitely be adapted to any situation, is to spell out a new c'tor like you do now.
It wasn't clear from your question if you are able to change the base class. Assuming you are, you might consider packaging up your base constructor arguments into a struct, which could be forwarded up from the derived constructor.
This is often seen when implementing the builder design pattern, which is one way to solve the telescoping constructor anti-pattern you're describing.
struct FooParts {
int i;
double d;
string s;
char c;
};
class Foo {
public:
Foo(FooParts const & parts) : parts(parts) {}
private:
FooParts parts;
};
class Derived : public Foo {
public:
Derived(FooParts const & parts, bool extra) : Base(parts), member(extra) {}
private:
bool member;
};
I'm not sure, from your question, if you realize that you can call the base constructor from your derived constructor. Using your example:
struct Window
{
Window(Window* parent, vec2 position, vec2 size, const String& name);
};
struct ConsoleWindow : Window
{
ConsoleWindow(Window* parent, vec2 position, vec2 size, const String& name, int otherValue)
: Window(parent, position, size, name)
{
// do something with `otherValue` here.
}
};
See for example here: calling the base class constructor in the derived class constructor
The most straightforward way to do what you described is to use the base class constructor in the initialization list of the derived class:
class Foo
{public:
Foo(int a, double b, std::string name, char somethingElse);
};
class Derived : public Foo
{
public:
Derived::Derived(int a, double b, std::string name, char somethingElse,
int _extraMember, char derivedSpecificThing) :
// Initialization list starts here
Foo(a, b, name, somethingElse),
extraMember(_extraMember)
{
// Do something with derivedSpecificThing etc.
}
private:
const int extraMember;
};
using Foo::Foo only exposes the constructor of the base class as an additional constructor for your derived class. Of course, the constructor of the base class cannot initialize the additional members of the derived class that it knows nothing about.
I have a base_class which has no default constructor, and I'd like to define a vector version of it (called derived_class). I know I should initialize the base_class constructor in my derived_class constructor, but the code below which attempts to initialize a vector with size dim and base_class(0,1) in each row cannot be compiled (it complains error: constructor for 'derived_class' must explicitly initialize the base class 'base_class' which does not have a default constructor), unless I add a default constructor (the commented line) to base_class. Do I miss or misunderstand something? Is there a way to make it work without defining the default base_class constructor?
#include <iostream>
#include <vector>
class base_class
{
public:
//base_class(){};
base_class(double a, double b){a_=a; b_=b;}
private:
double a_, b_;
};
class derived_class : public base_class
{
public:
derived_class(int dim): vector_object(dim, base_class(0,1)){};
std::vector<base_class> print_vector_object() {return vector_object;}
private:
std::vector<base_class> vector_object;
};
int main()
{
int dim = 3;
derived_class abc(3);
std::cout << abc.print_vector_object().size() << std::endl;
return 0;
}
UPDATE: I understand that I can totally avoid inheritance here in this simple case, but please assume that I do need inheritance for actual practice, thanks.
UPDATE2: As hinted by #vishal, if the constructor of derived_class is written as
derived_class(int dim) : base_class(0,0), vector_object(dim, base_class(0,1)) {};
The code can pass compiler. But I still don't understand why I have to initialize in this way...
Well, since you do not want to create default constructor in base class, you can call base constructor by:
derived_class(double a, double b, int dim) : base_class(a,b), vector_object(dim, base_class(0,1)) {};
Your vector_object is a red herring and has nothing to do with the problem, as you can verify with the following piece of code which will also make the compiler complain about the missing base_class default constructor:
class derived_class : public base_class
{
public:
derived_class(int dim) {} // error, tries to use `base_class` default constructor,
// but there is none...
};
You must either provide a default constructor or use a non-default one. In every instance of derived_class, there is a base_class sub-object, and the sub-object has to be created somehow.
One possible source of misunderstanding is the fact that objects in an inheritance hierarchy are initialized from top to bottom (base to derived). It may not seem logical at first sight, but by the time the derived_class constructor runs, the base_class sub-object must already exist. If the compiler cannot provide for this, then you get an error.
So even though the derived_class constructor specifies how the base_class sub-object is created, the actual creation of the sub-object happens before the creation of the derived_class part.
You are asking the following:
shouldn't the base_class object be initialized in my code?
Your code must initialize it, but it does not. You don't initialize it anywhere, and the default initialization does not work because the base class does not have a default constructor.
Sometimes, it helps to consider inheritance a special form of composition (there are indeed some striking similarities). The following piece of code suffers from the same problem as the one in your posting:
class base_class
{
public:
//base_class(){};
base_class(double a, double b){a_=a; b_=b;}
private:
double a_, b_;
};
class derived_class // <--- no inheritance
{
public:
base_class my_base; // <--- member variable
derived_class(int dim) {};
};
Would you still think that derived_class initializes the base_class object?
Another possible source of misunderstanding is the aforementioned red herring. You are saying:
I just don't understand why I cannot initialize it in a vector (...).
Because the vector member variable has nothing to do with the base_class sub-object, or with the public base_class member variable in my other example. There is no magical relationship between a vector member variable and anything else.
Taking your original piece of code again, a complete derived_class object can be pictured as follows in memory:
+-------------------+
| +---------------+ |
| | double | | <--- `base_class` sub-object
| | double | |
| +---------------+ |
+-------------------+ +--------+--------+--------+....
| std::vector ---------------> | double | double | double |
+-------------------+ | double | double | double |
+--------+--------+--------+....
^
|
|
a lot of other
`base_class` objects
The base_class objects managed by the vector are completely unrelated to the base_class sub-object that owes its existence to class inheritance.
(The diagram is a little over-simplified, because a std::vector normally also stores some internal book-keeping data, but that's irrelevant to this discussion.)
However, your code does not make a convincing case for inheritance anyway. So why do you inherit in the first place? You may as well do like this:
#include <iostream>
#include <vector>
class base_class
{
public:
//base_class(){};
base_class(double a, double b){a_=a; b_=b;}
private:
double a_, b_;
};
class derived_class // <--- no more inheritance (and thus wrong class name)
{
public:
derived_class(int dim) : vector_object(dim, base_class(0,1)){};
std::vector<base_class> print_vector_object() {return vector_object;}
private:
std::vector<base_class> vector_object;
};
int main()
{
int dim = 3;
derived_class abc(3);
std::cout << abc.print_vector_object().size() << std::endl;
return 0;
}
Are you sure, that a derived_class-object is a base_class-object and holds a vector of base_class-objects?
I assume, you actually only want a vector of base_class-objects. If that is true, don't derive derived_class from base_class. Actually that is where your compiler message comes from. It tells you, that you'll have to initialize the base_class aspect of your derived_class-object.
So here is my solution for you (beware, code is untested and will probably contain some bugs):
#include <iostream>
#include <vector>
class base_class
{
public:
// c++11 allows you to explicitly delete the default constructor.
base_class() = delete;
base_class(double a, double b):
a_{a}, b_{b} // <- prefer initializers over constructor body
{};
private:
double a_;
double b_;
};
class derived_class // <- this name is wrong now of course; change it.
{
public:
derived_class(int dim):
// better initialize doubles with float syntax, not int.
vector_object{dim, base_class{0.0, 1.0}}
{};
// Note: this will copy the whole vector on return.
// are you sure, that is what you really want?
auto print_vector_object() -> std::vector<base_class> {
return vector_object;
};
private:
std::vector<base_class> vector_object;
};
int main(int, char**)
{
// int dim = 3; <- this is useless, you never use dim.
auto abc = derived_class{3};
std::cout << abc.print_vector_object().size() << std::endl;
return 0;
}
Note: my code is meant to be C++11.
I have rewritten your class slightly
#include <iostream>
#include <vector>
class base_class {
private:
double a_, b_;
public:
//base_class(){};
base_class(double a, double b ) : a_(a), b_(b) {}
virtual ~base_class();
};
class derived_class : public base_class {
private:
std::vector<base_class> vector_object;
public:
explicit derived_class( int dim ) : base_class( 0, 1 ) {
vector_object.push_back( static_cast<base_class>( *this ) );
}
~derived_class();
std::vector<base_class> get_vector_object() const { return vector_object; }
};
int main() {
int dim = 3;
derived_class abc(3);
std::cout << abc.get_vector_object().size() << std::endl;
return 0;
}
This builds and compiles correctly. There were a few changes I made: I used the constructors member initializer list where applicable, I've added a virtual destructor to your base class; any time you inherit from a base class should have a virtual destructor, I moved all private member variables to the top of the class instead of at the bottom, I prefixed the derived_class constructor with the explicit keyword since you only have 1 parameter passed into it, I've changed the derived_class constructor to use the base_class constructor within its member's initialization list and I populated its member variable vector within the constructor using the push_back() method and statically casting the dereferenced this pointer to a base_class type, and I've also changed your print_vector_object method to just get_vector_object since it doesn't print anything and only return the member vector from the class. I also declared this method as const so that it doesn't change the class since you are only retrieving it. The only question that I have is what does the int parameter in the derived_class do? It is not used in any place and you have no member variable to store it.
This section of your derived class here
public:
derived_class(int dim): vector_object(dim, base_class(0,1)){};
where you declare your constructor is not making any sense to me.
It appears that you are trying to use the member initialization list to populate your vector member variable by passing in your derived class's passed in parameter and calling the constructor to your base class with values of {0,1}. This will not work as you would expect. You first have to construct your Base Class object which is a sub object to this derived class than within your constructor's function scope you can then populate your member vector.
What you have will cause a problem because you do not have a default constructor supplied that is available to try and construct your derived type. Since from what I can gather on what you have shown and what it appears what you are trying to do it seems that you want to have the base_class initialized to {0,1} when the derived constructor is called; if this is the case you can just call your implemented constructor for the base_class with {0,1} passed in its constructor while your derived type tries to be constructed. This will allow the derived_class to be constructed properly since the base_class has been constructed. Now that you are able to begin construction of your derived type it looks like you want to save the constructed base_class into your derived types vector member variable. This is why I do this within the constructor and not within the initialization list and I push_back an instance of the derived type that is statically casted back to a base type using the dereferenced this pointer. Also when I set a break point in the main function where you are trying to print its size and I look at derived_class's member variable it is populated with 1 object that has the values of a = 0 and b = 1. To be able to print these you would have to add public get methods to return each variable. Also if the int parameter in your derived class is not needed you can remove it along with the explicit keyword. You could also implement a second constructor for the derived type that takes in two doubles just as the base does and pass those parameters from the derived_class constructor to the base_class constructor like this:
public:
derived_class( double a, double b ) : base_class( a, b ) {
vector_object.push_back( static_cast<base_class>( *this ) );
}
I will demonstrate a simple example of a base and two derived classes where the first instance will have to set the values upon construction while the second will have to use its own constructor where there is no default constructor that is defined in the base class.
class Base {
private:
double x_, y_, z_;
public:
Base( double x, double y, double z );
virtual ~Base();
};
Base::Base() :
x_( x ), y_( x ), z_( z ) {
}
Base::~Base() {
}
class DerivedA : public Base {
private:
int value_;
public:
explicit DerivedA( int value );
~DerivedA();
};
// In This Case A Must Set The Values In The Constructor Itself: I'll Just
// Set Them To (0, 0, 0) To Keep It Simple
DerivedA::DerivedA( int value ) :
Base( 0, 0, 0 ),
value_( value ) {
}
DerivedA::~DerivedA() {
}
class DerivedB : public Base {
private:
int value_;
public:
DerivedB( int value, double x, double y, double z );
~DerivedB();
};
// In This Case B Doesn't Have To Know What Is Needed To Construct Base
// Since Its Constructor Expects Values From Its Caller And They Can
// Be Passed Off To The Base Class Constructor
DerivedB::DerivedB( int value, double x, double y, double z ) :
Base( x, y, z ),
value_( value ) {
}
DerivedB::~DerivedB() {
}
Let me know if this helps you out!
I am using a class say baseClass, from which I derive another class derivedClass. I have a problem definition that says, apart from others:
i) A member - object initialiser should be used to initialise a data member, say var1, that is declared in the base class.
ii) i) is done inside a base class constructor. It says, this has to be invoked only via a derived class constructor.
iii) The base class is an abstract class, whose objects cannot be created. But, I have a third class, inside which, I use:
baseClass *baseObjects[5];
The compiler does not report an error.
I do not understand, what i) and ii) really mean. An explanation in simple words would be fine. Also, any assistance on iii) is welcome.
Question 1:
Read about constructors : http://www.cprogramming.com/tutorial/constructor_destructor_ordering.html
Question 2:
Read about initialization list:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
Question 3:
Read about pointers to derived class:
http://www.learncpp.com/cpp-tutorial/121-pointers-and-references-to-the-base-class-of-derived-objects/
I think this way instead of just answering your question you could understand what's going on,
I think an illustration will be best.
i)
class A
{
int i;
public:
A(int ii) : i(ii) {}
}
The part i(ii) is an example of a member - object initialiser. Since C++ guarantees all constructors of members will be called before the constructor body is entered, this is your only way of specifying which constructor to call for each member.
ii) In C++ there is no super keyword. You must specify the base class as such:
class B : public A
{
public:
B(int i) : A(i) {}
}
That's partially due to the fact C++ allows multiple inheritence.
iii) Note that you haven't created any objects, only pointers to objects. And it's by this method polymorphism via inheritence is acheived in C++.
#include <iostream>
class Base
{
public:
Base(int i)
{}
virtual ~Base() = 0
{}
protected:
int i_;
};
class Derived: public Base
{
public:
Derived(int i, int j) : Base(i), j_(j)
{}
private:
int j_;
};
int main(int argc, char* argv[])
{
//Base b(1); object of abstract class is not allowed
Derived d(1, 2); // this is fine
}
As you can see i_ is being initalized by the Derived class by calling the Base class constructor. The = 0 on the destructor assures that the Base class is pure virtual and therefore we cannot instantiate it (see comment in main).
i) The following is what is known as an initializer list, you can use initializer lists to make sure that the data members have values before the constructor is entered. So in the following example, a has value 10 before you enter the constructor.
Class baseClass
{
int a;
public:
baseClass(int x):a(x)
{
}
}
ii) This is how you would explicitly call a base class constructor from a derived class constructor.
Class derivedClass : public baseClass
{
int a;
public:
derivedClass(int x):baseClass(x)
{
}
}
iii) You can't directly create instances of an abstract class. However, you can create pointers to an abstract base class and have those pointers point to any of its concrete implementations. So if you have an abstract base class Bird and concrete implementations Parrot and Sparrow then Bird* bird could point to either a Parrot or Sparrow instance since they are both birds.
C++11, ยง9/7:
A standard-layout class is a class that:
has no non-static data members of type non-standard-layout class (or array of such types) or reference,
has no virtual functions and no virtual base classes,
has the same access control for all non-static data members,
has no non-standard-layout base classes,
either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and
has no base classes of the same type as the first non-static data member.
So, is there a way to make a class with standard layout non-copyable? If yes, how?
Inheriting privately from boost::noncopyable will not work, because it made copy constructor private (hence not a standard layout). The boost::noncopyable's implementation is like this :
class noncopyable
{
protected:
noncopyable() {}
~noncopyable() {}
private: // emphasize the following members are private
noncopyable( const noncopyable& );
const noncopyable& operator=( const noncopyable& );
};
Because of the private section, it is not a standard layout class. I am also note sure if private inheritance break any standard layout rule.
#include <boost/noncopyable.hpp>
#include <iostream>
const int N = 50;
struct A
{
int data[N];
};
struct B : private boost::noncopyable
{
int data[N];
};
struct C
{
A data[10];
};
struct D : private boost::noncopyable
{
B data[10];
};
int main() {
std::cout<<sizeof(A)<<std::endl;
std::cout<<sizeof(B)<<std::endl;
std::cout<<sizeof(C)<<std::endl;
std::cout<<sizeof(D)<<std::endl;
}
The output is :
200
200
2000
2004
The example above shows that inheriting privately from boost::noncopyable changes the class into NOT standard layout compliant.
I am not sure if this is a g++ bug (I am using g++ 4.6.1), or the standard is somehow violated.
I think there is a confusion here:
the standard layout property is affected by attributes (and only attributes)
the copyable property is affected by methods (their presence, absence and accessibility)
The two concepts are orthogonal.
UPDATE:
The following display the very same behavior that boost::noncopyable:
#include <iostream>
struct foo {};
struct B : foo { int data; };
struct D : foo { B data; };
int main() {
D d;
std::cout << (char*)(&d.data) - (char*)(&d) << "\n";
}
The result is 4.
I believe this is because of:
has no base classes of the same type as the first non-static data member.
Indeed, experiment shows that introducing a int a; in D prior to data does not increases its size. I think that the fact that B inherits from foo means that data (first non-static data member) is considered to be the same type as foo (base class of D).
This leads to an ambiguity: foo* f = &d would have the same address as foo* g = &b.data; if the compiler did not introduce this padding.
There are two things you need to do to make your class non copyable:
Make the copy constructor private.
Make the assignment operator private. (Where it gets assigned another type of the same kinds as the class itself).
You don't need to inherit from some boost class just to get that behavior.
And may I add, who cares about some fancy 'standard layout' idea. Program what you need and don't succumb to this extreme space theory.
I was wondering how to do something in C++. I want to be able to create an instance of this struct
struct ComplexInstruction : simple_instr
{
bool isHead;
bool isTail;
};
that copies all the data from the simple_instr instance. So essentially, I want to do something like this
ComplexInstruction cInstr = instr; // <- instance of simple_instr
and have cInstr have a copy of all the data in instr without having to copy over every field (since there's alot of them). I'm not sure how do this, and I don't think simple casting will work. Additionally, is it possible to do the reverse? I.e. have an instance of ComplexInstruction and turn it into an instance of simple_instr. I assume this can be done using casting, but I don;t have alot of experience with c++
Thanks in advance
Create a consctructor in the derived class to initialize from a base class.
class Base
{
int x;
public:
Base(int a) : x(a){}
};
class Derived : public Base
{
public:
Derived(const Base & B) : Base(B){}
};
Note that if you have a derived object of Base, you actually have a base object and you can safely use the base copy ctor like so.
Derived d;
Base b(d);//the parts of Base that are in Derived are now copied from d to b.
//Rest is ignored.
If you want to be more verbose, you write an operator= in your derived class like
void operator=(const Base & b)
{
Base::operator=(b);
//don't forget to initialize the rest of the derived members after this, though.
}
It all depends on what you want to do, really. The important thing is: be explicit. Don't leave uninitialized members of your class.
You need to provide a constructor that takes an argument that is convertible to const simple_instr&:
struct simple_instr {
int i;
simple_instr(): i(0) { }
explicit simple_instr(int i): i(i) { }
};
struct ComplexInstruction: simple_instr {
explicit ComplexInstruction(const simple_instr& simple):
simple_instr(simple), isHead(false), isTail(false) { }
bool isHead;
bool isTail;
};
int main() {
simple_instr instr;
ComplexInstruction cInstr(instr);
}
Here I chose an explicit constructor, but depending on the semantics, an implicit one could also be appropriate. Only if the constructor is implicit, the =-style initialization works without casting.
Edit: This is not the best way to accomplish this, please look at the other answers.
This will do what you are looking for.
struct ComplexInstruction : simple_instr
{
ComplexInstruction(const simple_instr &simple)
{
*((simple_instr*)this) = simple;
}
bool isHead;
bool isTail;
};
Then ComplexInstruciton complex = simple; will call the conversion constructor. ComplexInstruction's copy construct casts this to its base class and the = will call simple_instr's copy constructor, which by default is a bitwise copy.