Calling object constructors without using new

Started by
11 comments, last by Khatharr 11 years, 4 months ago
In C++ I am wondering if this is possible or not.

I have an object... MyObject
it has a constructor MyObject::MyObject(string objName){ }

Suppose I need to use this object, within another class....

class OtherClass
{
MyObject obj1;
MyObject obj2;
}

This will give me an error, because its wanting it to look like...

class OtherClass
{
MyObject obj1("first name");
MyObject obj2("second name");
}

However, I wont know what first name, and second name are until later in the program

I could do this.....

class OtherClass
{
MyObject* obj1;
MyObject* obj2;
}
... then later on ....
OtherClass otherClass; otherClass.obj1 = new MyObject("first name"); etc.....

But I would really like to have the actual object, and not a ptr to an object.
Is it possible, or am I forced to use pointers.

Thanks.
Advertisement
Keep the objects as objects and not pointers, and use an initializer list in the constructor of OtherClass.

EDIT: By the way, the syntax you think the compiler wants wouldn't work...
One quick solution could be to rewrite the class to not take any parameters, set a default value in the constructor and then use set-functions to change to the correct name once you know it.

But I would really like to have the actual object, and not a ptr to an object.
Is it possible, or am I forced to use pointers.


No need to use pointers, but you'll need to implement the default constructor of OtherClass like this:
[source lang="cpp"]class OtherClass
{
OtherClass();
MyObject obj1;
MyObject obj2;
};

OtherClass::OtherClass()
: obj1("first name")
, obj2("second name")
{
}
[/source]
OtherClass::setName(MyObject& whichObjectsNameToChange, std::string Name, WhichNameToPut)
{
whichObjectsNameToChange.name = WhichNameToPut;
}
Simple no?
or have each object have setName function

EDIT:
May downvoters explain why they disagree with set function?
Oooooh, I see....
So, its sort of like when you create a constructor for a derived class from a base class. With the dreivedClass : baseClass

Thanks so much.

OtherClass::setName(MyObject& whichObjectsNameToChange, std::string Name, WhichNameToPut)
{
whichObjectsNameToChange.name = WhichNameToPut;
}
Simple no?
or have each object have setName function

EDIT:
May downvoters explain why they disagree with set function?


Trivial accessors and mutators are wasted code.

Also, two-phase construction is usually a massive anti-pattern.

You should always create your objects in a sane state, and always maintain that sanity by upholding class invariants. Use of trivial mutators means you have violated encapsulation in most cases, and use of two-phase construction is fundamentally counter to this goal in and of itself.


(There are times when two-phase construction is acceptable. This is not one of them.)

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]


Trivial accessors and mutators are wasted code.

Also, two-phase construction is usually a massive anti-pattern.

You should always create your objects in a sane state, and always maintain that sanity by upholding class invariants. Use of trivial mutators means you have violated encapsulation in most cases, and use of two-phase construction is fundamentally counter to this goal in and of itself.


(There are times when two-phase construction is acceptable. This is not one of them.)


I've moved to the pattern of having the ctor establish sanity and then having an initialize() or load() function (depending on the class type) to actually initialize the object for use. Basically I'm avoiding 'work' in the ctor because it's been so problematic in the past and makes error control nasty looking. I still allow for simple initial values to be passed to ctors in cases where it doesn't create work, though. Mainly I guess I just feel uncomfortable in cases where I've got several automatics in a class and that a single one of them throwing in its ctor during the composing class' ctor will create increasingly nasty try/catch blocks in ctor chains. Would you recommend against this or does that make sense?
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.
Exception safety is a tough - and ultimately subjective - decision in any C++ code base.

Basically, my opinion is: either do exception safety right, or don't mess with it at all. If you want exception safety, use RAII, don't use two-phase construction, and throw from your constructors as necessary. If you don't want to handle all the ugly corner cases of exception handling in C++ (and who does?) then just ignore exceptions and let them crash the program if and when they are thrown (or turn them off and forbid them entirely). If you do that, you should use RAII for encapsulation and don't use two-phase construction because you don't need to worry about anything throwing.

So basically, IMHO (and I'm sure others have different opinions) two-phase construction is only useful if you're trying to do exceptions and not do exceptions at the same time.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Typically I only try to catch std::bad_alloc and return an error code from the offending function. Other exceptions I'm leaving unhandled for now, though I may place a try/catch in my main at a later point just to pop an error message.

I may actually switch to just disabling exceptions since I honestly preferred it when allocators returned NULL instead of throwing. I guess I'll think about it some more.

I've gotten comfortable with RAII and that's gone a long way in alleviating exception related stress issues (my fingernails have grown back!) but the ctors calling ctors calling ctors was becoming pretty crazy in terms of nasty looking ctor chains that felt really brittle. Not being able to return a code from a ctor is the real problem for me. If I know that some process may fail (file not found, memory not allocated, etc) then there's no way to communicate failure down the ctor chain without using exceptions. RAII helps with the problem of not having dangling resources when the failure happens, but it doesn't provide a way to communicate the failure down the chain.
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

This topic is closed to new replies.

Advertisement