• FEATURED

View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

# C++ Inheritance confusion

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

11 replies to this topic

Posted 25 February 2014 - 01:42 PM

This has got to be a simple mistake, but I've stared at it for too long now and I just don't see it.  (Excuse the canned example; it's pretty close to the real thing though.)

class Foo {

public:
Foo(vector<string> things, string place) : m_thingList(things)
{
log("in Foo ctor");
validatePlacePriorToAssignment(place);
}

virtual ~Foo() {}

private:

vector<string> m_thingList;
string m_validatedPlace;

validatePlacePriorToAssignment(string p)
{
// do stuff to validate place; if not valid, throw exception
// else
m_validatedPlace = p;
}
...
};

class Bar : public Foo {
public:
const string defaultPlace = "Validville";
Bar(vector<string> stuff) : Foo(stuff, defaultPlace)
{
log("in Bar ctor");
}
...
};

someFunctionSomewhere(vector<string> allTheThings) {
try { Bar barbar(allTheThings); }
}


Okay, here's the weirdness I'm seeing: there is a log entry for the Foo ctor but not the Bar ctor. I'm stack-allocating a member of a derived class; my understanding is that the base ctor is called THEN the derived ctor is called...but in this case that doesn't seem to be happening!

I'm worried that I'm doing inheritance wrong, or using initializer lists wrong, or I'm  using them wrong in the context of inheritance, or for some reason it's wrong (not allowed) to validate prior to assigning in a constructor. I think I'm doing this all correctly, but obviously I'm not so here I am.

I've read through a bunch of tutorials and stackoverflow examples this afternoon, and - for the life of me - I can't figure out why this isn't working; it looks like all the sample code. If you can catch it, I'd be especially grateful.

I was previously serratemplar; a name I forfeited to share a name with an angry rank-bearing monkey.

Posted 25 February 2014 - 02:01 PM

Removing the init lists entirely results in the kind of behavior I'd expect, i.e. I see log entries from both ctors and in the order I'd expect (Foo then Bar).

I was previously serratemplar; a name I forfeited to share a name with an angry rank-bearing monkey.

### #3Servant of the Lord  Members

Posted 25 February 2014 - 02:11 PM

It looks correct. Is the exception being triggered? Maybe "validatePlacePriorToAssignment(place);" is crashing and you aren't realizing it.

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

Posted 25 February 2014 - 02:21 PM

That's got to be it! I commented out the validate() call and just set the member in the init list. So...good. Thank you for being a sanity check for me, haha.

A little odd; I thought for sure I was catching there, but I am demonstrably incorrect. I was looking in the very wrong place.

Thank you!

I was previously serratemplar; a name I forfeited to share a name with an angry rank-bearing monkey.

### #5Servant of the Lord  Members

Posted 25 February 2014 - 02:31 PM

This crashes. This runs. I think it's related to the constant string.

//This will be constructed when 'Bar's constructor is ran.
const string defaultPlace = "Validville";

//But you are passing it to 'Foo's constructor before it gets constructed,
//because Foo's constructor runs before Bar's constructor.
//So 'defaultPlace' is invalid, and it crashes.
//
//If you made it static-const, then it'd be fine (as long as no Bar's are static or global).
Bar(vector<string> stuff) : Foo(stuff, defaultPlace)
{
std::cout << "in Bar ctor" << std::endl;
}


Sneaky little bug.

Glad I could be of help!

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

Posted 25 February 2014 - 02:41 PM

That (const string bug) was actually a second bug, well shielded by the first one.

I fixed it with stackoverflow: http://stackoverflow.com/questions/1563897/c-static-constant-string-class-member

In short, it's now declared (static const) in the class decl, then defined in the cpp file, but still scoped to the class (which is what I wanted).

Second set of eyes for the win. Nice to see it running again.

I was previously serratemplar; a name I forfeited to share a name with an angry rank-bearing monkey.

### #7SunDog  Members

Posted 25 February 2014 - 02:50 PM

This is the reason I usually stick with trivial, or even empty, constructors, and then call an explicit init() function after instantiation.  Constructos, exceptions, and manual memory management are a really bad combination :-) .  The problem is even worse for destructors.

### #8Servant of the Lord  Members

Posted 25 February 2014 - 03:02 PM

Not using constructors in favor of init() is like dodging a car to get hit by a train. It doesn't make things safer, it's just a different set of errors to look out for.

RAII is a really important and incredibly useful tool for code safety.

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

### #9frob  Moderators

Posted 25 February 2014 - 09:27 PM

Note that RAII and constructors that build an empty state are not contradictory. You can absolutely construct empty, disconnected objects that are still well formed and initialized to a known state. Empty containers and disconnected file streams are the most obvious examples of this. You wouldn't say a constructor for a std::vector does not follow RAII just because array data was not assigned, or a std::ifstream is ill formed because the .open() function hasn't been called yet. They are fully initialized objects that are ready for use.

Constructing a logger which is not yet connected to any streams can be a very good thing; many major logging systems do exactly that.

A logger is often little more than a listener pattern. Output streams get registered as listeners, and when logging data is sent to the system any active listeners can process the data. The collection of output streams can be zero in size, or it can be large. Streams can in theory be added and removed dynamically. Constructing the logger with an empty collection of streams is fully initialized. Just because nobody is listening does not make it undefined to handle a log event; it simply forwards the event to all (currently zero) listeners.

Edited by frob, 25 February 2014 - 09:48 PM.
More on why it is perfectly valid.

Check out my book, Game Development with Unity, aimed at beginners who want to build fun games fast.

Also check out my personal website at bryanwagstaff.com, where I occasionally write about assorted stuff.

### #10Servant of the Lord  Members

Posted 25 February 2014 - 09:57 PM

That's true. Another reason for an init()-type function is to reuse the memory of same class instance rather than deleting and then allocating a new object, or to intentionally delay some heavy operation until a more convenient time.

I meant that avoiding constructors and destructors because they can cause bugs if misused doesn't mean your code will be safe - you'll just be looking at a different set of bugs. Constructors and destructors go hand in hand with memory management.

Using an init() function when it is part of the class's desired interface makes sense. Using an init() function solely because you don't like constructors doesn't make sense. Doubly sole for destructors.

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

Posted 26 February 2014 - 08:33 AM

So, while we're on the topic, what are the direct thoughts on my design there? I.E. using a validator (and potentially throwing) from the constructor (the latter an idea I got from Scott Meyer, iirc) vs. constructing empty then compelling the user to fill in the blanks prior to calling run().

The reason I wanted to have the constructor do the validation and bomb gracefully upon a fail is that I want the interface here to be very difficult to use incorrectly, and there's (at least) two parts to that, which I see: fewer calls need to be made (less internals exposed) and it still prevents you from doing something bonkers (in my example there, you can't do any object-supported operations on your list of things if the place isn't valid).

think that, were I to allow empty construction then push init responsibility to the user, there's not much of a difference: init() could throw instead of the constructor, and you'd still have an object in an empty/usable state. (That has some appeal.) I'm honestly not clear on what the right answer to this is.

I was previously serratemplar; a name I forfeited to share a name with an angry rank-bearing monkey.

### #12frob  Moderators

Posted 26 February 2014 - 11:42 AM

RAII says to initialize your data, and to this I agree.

It is in contrast to other languages (such as C) where a structure can be created but initially contains unspecified garbage, just whatever happened to be in memory at the time. Empty is initialized, random unspecified garbage is uninitialized.

People who come from a more modern language background (C#/Java/Python) are used to members being automatically initialized for you, so when they see RAII they interpret it differently than it was meant. Back in the day when the alternative meant having unspecified values, including invalid values that looked like valid values, RAII meant creating an allocation function that allocated memory and then immediately called something like bzero() or memset() or otherwise immediately assigning valid values if zero is not appropriate, then returned the initialized resource.

In my experience it is fine to allow a convenience non-default constructor if you want, but beware of error conditions.

It is generally best to have a default constructor that only creates and empty object. This way when someone allocates an array or temporaries or other quick-to-do things, they immediately get back the objects without any fuss.

If you want to provide an additional constructor that builds up an object based on additional data you can do so but it adds complexity. Now you have a constructor that is likely to have error conditions (so you may need to throw based on all possible error conditions, in turn forcing you to catch all the exceptions that might be thrown at construction time). Such a constructor takes more time and blocks execution. Such a constructor generally makes some things a little more complicated in exchange for convenience in another area. Yes, for some things there is no additional cost and the difference is that the values are assigned to only once rather than twice; for other objects, however, the cost to the application can be quite large. When such a constructor requires trips to disk, trips to the network, or any other long-running or blocking behavior, I generally question its necessity.

Edited by frob, 26 February 2014 - 11:44 AM.

Check out my book, Game Development with Unity, aimed at beginners who want to build fun games fast.

Also check out my personal website at bryanwagstaff.com, where I occasionally write about assorted stuff.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.