how to make my function accept both const char* and string

I have a function in my class:

1
2
3
4
Serial::Serial(std::string* portname)
{
	file.open(portname->c_str());
}


do I have to write this function 2 times to make it accept both
Serial test("ttyACM0");
and Serial test(thestring i made); ?
you can make an overloaded function....
Why are you passing the string by pointer? If you instead pass the string by const reference it will automatically construct and pass a string object when you pass a char*.

1
2
3
4
Serial::Serial(const std::string& portname)
{
	file.open(portname.c_str());
}
Last edited on
What is the difference between & and the * i used? And i tried constant pointer, it didn't work (wasn't expecting it to :D)
And peter i already knoe i can do that, this was mostly out of curiosity and because i already remeber seeing some library likre that (opengl related or something )

I used pointer for performance, it doesn't create a copy that way!
I used pointer for performance, it doesn't create a copy that way!


Neither does reference (&) - http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/

Neither does reference (&) - http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/


:o thanks TarikNeaj and Peter87!
Last edited on
With modern C++, with move semantics, passing a string doesn't make a deep copy either, so there's nothing wrong with doing that.
With modern C++, with move semantics, passing a string [by value] doesn't make a deep copy either, so there's nothing wrong with doing that.

That is only true when passing a rvalue-reference. If you pass a string variable (without using std::move or similar) to a function that takes the string argument by value it would still have do a deep copy.
Last edited on
Topic archived. No new replies allowed.