Constructor overloading with optional arguments

Oct 6, 2010 at 2:25pm
I am working on a "Name" class in which a name is composed of 3 "String" objects. This builds upon a previous exercise in which we created our own "String" class. I have two constructors, one of which copies an existing name object and another which accepts three "String" objects to create an name. If I pass (const Name &) everything works. Also, if I pass 3 "String" objects everything works. The constructor used for passing 3 "String" objects is supposed to be able to have two of the arguments optional (const String & F = String (""), const String & M = String ("") with (const String & L) being a required argument. But, when I run the program only passing a single "String" object it uses the "Name" copy constructor and therefore says it can't convert parameter 1 from 'String' to 'const Name &'. I tried using the explicit keyword for the '3 String object' constructor but it didn't help. Can the compiler not see that I am passing a "String" object instead of a "Name" object and choose the appropriate constructor? Any help working around this? Thanks in advance.

1
2
3
4
5
6
7
8
9
10
//Name.h

class Name
 {
 public:
     Name();
     Name(const Name &);
     Name(const String &, const String &, const String &);
     ~Name();
 };


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Name.cpp
Name::Name (): NameData (0)
	{
	}

Name::Name(const Name & N): First (N.First), Middle (N.Middle), Last (N.Last), NameData (0)
	{
	}


Name::Name(const String & L, const String & F = String (""), const String & M = String ("")): First (F), Middle (M), Last (L)
	{
	NameData = 0;
	}

Name::~Name()
	{
	}


1
2
3
4
//Main.cpp

String S1 ("Johnson");
Name N4 (S1);



Oct 6, 2010 at 2:41pm
The compiler doesn't see the contents of Name.cpp when compiling Main.cpp, so it can't possibly know that there are any default arguments. These are useless in Name.cpp and actually belong in Name.h.
As it is now, the compiler just sees one constructor that takes one argument - and that is the copy constructor.
So it will try to convert the string to a Name object, which isn't possible.
Last edited on Oct 6, 2010 at 2:44pm
Oct 6, 2010 at 2:47pm
Thanks Athar!

I moved the constructors into Name.h and it works as expected.
Topic archived. No new replies allowed.