tags:

views:

72

answers:

2

I've put together a simple C++ "Hello World" program to practice; unfortunately, upon compilation I get a few errors:

expected ')' before fName

error: prototype for 'HelloWorld::HelloWorld(std::string, std::string)' does not match any in class 'HelloWorld'

Below is my code, can anyone help me understand what I'm missing/overlooking? Thanks.

Header:

  1 #ifndef HELLOWORLD_H_ 
  2 #define HELLOWORLD_H_
  3 #include <string>
  4 
  5 class HelloWorld
  6 {
  7     public:
  8         HelloWorld();
  9         HelloWorld(string fName, string lName);
 10         ~HelloWorld();
 11 };
 12 
 13 #endif

Implementation:

  1 #include <iostream>
  2 #include <string>
  3 #include "HelloWorld.h"
  4 
  5 using namespace std;
  6 
  7 HelloWorld::HelloWorld()
  8 {
  9     cout << "Hello, anonymous!";
 10 }
 11 
 12 HelloWorld::HelloWorld(string fName, string lName)
 13 {
 14     cout << "Hello, " << fName << ' ' << lName << endl;
 15 }
 16 
 17 HelloWorld::~HelloWorld()
 18 {
 19     cout << "Goodbye..." << endl;
 20 }
+10  A: 

You need to change your header file to reference std::string instead of string because they are defined inside the std namespace.

HelloWorld(std::string fName, std::string lName);

It works in your .cpp file because you specifically import this namespace. The solution however is not to import this namespace in your header file (generally speaking a bad idea in C++).

JaredPar
If you must, you can import individual names, like `using std::string`. I'd still be reluctant, but it doesn't defeat the whole purpose of using a namespace.
David Thornley
Are there any situations were importing namespaces into the header file is advisable?
Jonny
@Jonny: In real code, none that I can think of.
John Dibling
even `using std::string` isnt such a good idea its always better to use std::string in the declarations in header files
Yogesh Arora
+3  A: 

If the code is exactly like what you pasted into the question, the most probable cause of the error is that in the header, the compiler is not identifying what string means, as it is not a symbol in the global namespace. Try fully qualifying it:

class HelloWorld
{
//...
   HelloWorld( std::string fName, std::string lName );
};
David Rodríguez - dribeas