Jump to content

  • Log In with Google      Sign In   
  • Create Account


Calling object constructors without using new


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.

  • You cannot reply to this topic
12 replies to this topic

#1 SelethD   Members   -  Reputation: 390

Like
0Likes
Like

Posted 03 December 2012 - 12:00 PM

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.

Sponsor:

#2 Álvaro   Crossbones+   -  Reputation: 12383

Like
1Likes
Like

Posted 03 December 2012 - 12:04 PM

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

Edited by Álvaro, 03 December 2012 - 12:04 PM.


#3 Celiasson   Members   -  Reputation: 492

Like
0Likes
Like

Posted 03 December 2012 - 01:32 PM

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.

#4 Rattenhirn   Crossbones+   -  Reputation: 1690

Like
4Likes
Like

Posted 03 December 2012 - 01:43 PM

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]

Edited by Rattenhirn, 03 December 2012 - 01:44 PM.


#5 BaneTrapper   Members   -  Reputation: 1141

Like
-3Likes
Like

Posted 03 December 2012 - 02:03 PM

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?

Edited by BaneTrapper, 03 December 2012 - 03:26 PM.

Current projects:
The Wanderer, 2d turn based rpg style game

www.gamedev.net/topic/641117-check-up-the-wanderer/


#6 SelethD   Members   -  Reputation: 390

Like
0Likes
Like

Posted 03 December 2012 - 02:10 PM

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.

#7 ApochPiQ   Moderators   -  Reputation: 14623

Like
1Likes
Like

Posted 03 December 2012 - 04:45 PM

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

#8 Khatharr   Crossbones+   -  Reputation: 2914

Like
0Likes
Like

Posted 03 December 2012 - 07:19 PM

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.

#9 ApochPiQ   Moderators   -  Reputation: 14623

Like
4Likes
Like

Posted 03 December 2012 - 07:30 PM

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.

#10 Khatharr   Crossbones+   -  Reputation: 2914

Like
0Likes
Like

Posted 03 December 2012 - 08:11 PM

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.

#11 BaneTrapper   Members   -  Reputation: 1141

Like
0Likes
Like

Posted 04 December 2012 - 03:03 AM

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

Kind of you, much to learn i have.

Current projects:
The Wanderer, 2d turn based rpg style game

www.gamedev.net/topic/641117-check-up-the-wanderer/


#12 BitMaster   Crossbones+   -  Reputation: 3771

Like
0Likes
Like

Posted 04 December 2012 - 03:21 AM

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 feel bound to ask why. I don't think I have ever experienced legitimately running into std::bad_alloc. For me it only ever happened as a side effect of a bug that really should be dealt with directly or trying to process a huge dataset not as out-of-core as it was planned to be.
I don't really understand returning an error code either. If something goes wrong because no more continuous memory is available then the most sensible thing to do is A) giving up, because this machine does not seem to have to resources we need, or B) catching the exception at a sensible location and calling as many "clear your caches NOW" as possible. Sure, I can do that with an error code but why should I bother propagating that up the callstack if the exception can do exactly that automatically?
Mobile phones and other embedded devices might be something else but in my (admittedly limited) experience they seem to prefer telling you in some other way if you start getting too memory-greedy for them and even then an std::bad_alloc should not really happen.

Edit: and if you really want a non-throwing behavior from new, why don't you use std::nothrow?

Edited by BitMaster, 04 December 2012 - 03:25 AM.


#13 Khatharr   Crossbones+   -  Reputation: 2914

Like
0Likes
Like

Posted 04 December 2012 - 04:07 AM

As for what you mentioned about memory recovery that's why I'm considering it rather than having already done it.

As for nothrow - and this is the best reason ever (only half sarcastic here) - I don't like the syntax.
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.




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.



PARTNERS