Maximosaic
Maximosaic

Reputation: 634

Objects as default values in c++

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?

Upvotes: 4

Views: 175

Answers (3)

GioLaq
GioLaq

Reputation: 2547

You could use overloading:

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

Upvotes: -2

stefaanv
stefaanv

Reputation: 14392

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.

Upvotes: 7

andre
andre

Reputation: 7249

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.

Upvotes: 3

Related Questions