parameterized constructor

Is there any process in c++ by using which I can initialize my class object after declare where my class has parameterized constructor .
For example :
class myclass{
private:
string name;
public:
myclass(){
name="No Name";
}
myclass(string iname){
name= iname;
}


};
int main()
{
myclass abc;//we know this will call our default constructor .
myclass aab("name");//this will call our parameterized constructor .
}
Now my question is if C++ has any way so that i can call my parameterized constructor before declare my class object.
for simplicity my question is quiet similar like below code
i want to find any way so that i can call like below
int main()
{
myclass hello;
hello("name");//i want to call my parameterized constructor here.
}
is there any process like that please tell me that
Last edited on
Use a setName method because the object hello has already been instantiated/constructed and you can’t have 2 hello objects. Why would you even if it was possible?
Once an object is constructed the constructor will not be called a again. However you may overload the operator() like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class myclass{
private:
string name;
public:
myclass(){
name="No Name";
}
myclass(string iname){
name= iname;
}

// Note: overloaded operator()
void operator()(string iname){
name= iname;
}

};
Now you can use it like in the second main()
delay declaration until the point of initialization to avoid these useless state object

may also use the assignment operator
1
2
3
myclass hello;
//...
hello = myclass("name");
Thanks bro
This two method are working
But for the first method it's call the default constructor
if i want to call 2nd constructor instead of default constructor is there any process @coder777 bro?
and for the second method it's call both default constructor and 2nd constructor with parameter
is there any process to to call only single constructor with the same process @me555 bro??
Last edited on
@againtry bro i just curious to know that
Consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <string>
#include <iostream>

class Myclass {
private:
	std::string name {"No Name"};

public:
	Myclass() {}

	Myclass(const std::string& iname) : name(iname) {}

	void operator()(const std::string& iname) {
		name = iname;
	}

	std::string operator()() const {
		return name;
	}
};

int main()
{
	Myclass c1;

	std::cout << c1() << '\n';

	c1("new name");

	std::cout << c1() << '\n';

	Myclass c2("another name");

	std::cout << c2() << '\n';
}


which displays:


No Name
new name
another name

Topic archived. No new replies allowed.