4

is there a way to have a default Object for parameters in C++ functions? I tried

void func(SomeClass param = new SomeClass(4)); 

and it worked. However how would I am I supposed to know wheter I have to free the allocated memory in the end? I would like to do the same without pointers, just an Object on the stack. is that possible?

7
  • 1
    I don't see any explicit pointer here Commented Jan 16, 2013 at 16:27
  • to avoid pointers, memory allocation and so on, you can use this: void func(SomeClass param = SomeClass(4));. Your function will receive SomeClass object by value and will destroy it automatically after the function call Commented Jan 16, 2013 at 16:28
  • Does SomeClass have an implicit constructor from SomeClass* ? Commented Jan 16, 2013 at 16:29
  • how does it worked ? new SomeClass(4) returning a pointer to SomeClass while the function expect an instance. but without the new there is no problem. +1 since I never thought of trying this before. Commented Jan 16, 2013 at 16:30
  • 1
    @CashCow or worse, a SomeClass( void * ) There's a train-wreck waiting to happen. Commented Jan 16, 2013 at 16:31

3 Answers 3

7
void func(SomeClass param = new SomeClass(4)); 

This can't work because new returns a pointer

void func(SomeClass param = SomeClass(4)); 

should work and the object doesn't need to be freed.

Sign up to request clarification or add additional context in comments.

2 Comments

It can work if SomeClass has a constructor that takes SomeClass*. I admit that is unlikely, and I use the word "work" very loosely.
@BenjaminLindley: Nice addition, a bit scary.
3

You almost had it but you don't need the new keyword.

void func(SomeClass param = SomeClass(4)); 

This method has the advantage over using new in that it will be automatically deleted at the end of a call so no memory management is needed.

An alternative is to use shared pointers.

Comments

-2

You could use overloading:

void func(const SomeClass&) const; void func() const { SomeClass* param = new SomeClass(4); func(param); delete param; } 

2 Comments

At least use pointers and delete afterwards, if you want this approach
SomeClass param = new SomeClass(4); does not work as new returns a pointer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.