Can a class constructor becalled like a method?

Hi,
when the below is done, does it call the constroctor only, and if yes, constructors do not have return types so how does it work? is there anything behind the scene?

wxAddHandler(new wxPNG_HANDLER);
and
sf::RenderWindow(sf::VideoMode(...),...);

Aceix.
Constructor of type T constructs an object of type T. It may not return a value like regular functions, but a value you will get.

That new T returns a pointer to an object that is of type T.

For more fun:
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr387.htm
I'm not sure I follow your code. Lets take this class for instance:

foo.h:
1
2
3
4
5
6
7
class foo
{
private:
	int a;
public:
	foo(int);
};


foo.cpp
1
2
3
4
5
6
7
foo::foo(int a)
{
	/* store integer a */
	this->a = a;
	
	std::cout << "foo constructor called!" << std::endl;
};


With that class you can call the constructor for foo in many different ways:
foo newfoo = foo(0); or foo *newfoo = new foo(0); or foo(0);

However, from my understanding of constructors, constructors cannot and should not ever be called like this:

1
2
foo newfoo = foo(0);
newfoo.foo(1);


This is because constructors are supposed to handle the construction of an object from a class. From what I interpret from this, is that constructors are meant to flesh out an object during creation to prevent errors and shorten the code. This means that the constructors are not supposed to take the place of a method.

Edit: I'm 99% sure that you can't return a value from the constructor, because the object of the class is that value being returned.
Last edited on
Thanks. So you mean my first code creates a dynamic object, and the second creates a normal object?

Aceix.
Yes

In this case, an anonymous temporary instance of class sf::VideoMode is constructed and passed as the first parameter.

sf::RenderWindow(sf::VideoMode(...),...);

Andy
Thank you all!

Aceix.
Fun fact: c-style casts and functional casts are both constructor calls.
Topic archived. No new replies allowed.