Followers 0

# C++ Inheritance confusion

## 11 posts in this topic

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.

1

##### Share on other sites

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).

0

##### Share on other sites

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

2

##### Share on other sites

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!

2

##### Share on other sites

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.

0

##### Share on other sites

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.

0

##### Share on other sites

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.

0

##### Share on other sites

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.

0

##### Share on other sites

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
2

## Create an account

Register a new account