vanchagreen
vanchagreen

Reputation: 410

Using the new operator with an object's non-default constructor

Would something like:

classname* p = new classname(parameter1, parameter2, ...); 

create a pointer that points to an object initialized using a non-default constructor with signature: classname(parameter1, parameter2, ...)?

Thanks!

Upvotes: 3

Views: 1937

Answers (4)

user1199657
user1199657

Reputation:

Yes it does. but may I know how did the question came to your mind? you got some errors?

Upvotes: 0

twsaef
twsaef

Reputation: 2121

Yes, it will. This program illustrates the concept.

#include <string>
#include <iostream>

class Foo
{
private:
    std::string name;
public:
    Foo() : name("default"){}
    Foo(std::string Name): name(Name) {}

    void Print() { std::cout << name << std::endl; }
};

int main ()
{
    Foo* foo = new Foo();
    foo->Print();
    delete foo;

    foo = new Foo("special");
    foo->Print();
    delete foo;
}

The output is:

default
special

Upvotes: 1

Alex Z
Alex Z

Reputation: 2590

Couldn't have put it better myself - remember to delete it when finished with it though, unless you want to make the heap unhappy!

Upvotes: 1

CB Bailey
CB Bailey

Reputation: 791779

Yes, that is correct.



Upvotes: 4

Related Questions