Example of Polymorphism

Sep 7, 2009 at 9:06am
Hi,

I'm a newbie in CPP and I'm having trouble in understanding how polymorphism works in CPP. I've programmed an example but it won't compile, and I can't understand why.

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <cstdlib>
#include <iostream>
#include "hello.h"

using namespace std;

int main(int argc, char *argv[])
{
 	Hello h;
 	h.put();
    system("PAUSE");
    return EXIT_SUCCESS;
}


hello.h
1
2
3
4
5
6
#include "phrase.h"

class Hello: public Phrase {
  public:
    void put();	  
};


hello.cpp
1
2
3
4
5
6
7
8
9
#include "hello.h"
#include <iostream>

using namespace std;

void Hello::put()
{
  phrase("Hello");
};


phrase.h
1
2
3
4
5
6
7
#include <string.h>
#include <iostream>

class Phrase {
  public:
   void phrase(string *p);	  
};



phrase.cpp
1
2
3
4
5
6
7
8
9
#include "phrase.h"

using namespace std;

void Phrase:: phrase(string *p)
{
  cout << p << endl;		 
  return 1;
}


What am I doing wrong?

Thanks,
Pedro
Sep 7, 2009 at 9:16am
What do the errors say?
Sep 7, 2009 at 9:36am
I can't understand the errors, this is why I haven't post it in the first message. I compile the code with Dev-C++ editor and it got me these errors:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Compiler: Default compiler
Building Makefile: "D:\cpp_workspace\Teste\Makefile.win"
Executing  make...
make.exe -f "D:\cpp_workspace\Teste\Makefile.win" all
g++.exe -c main.cpp -o main.o -I"D:/Dev-Cpp/lib/gcc/mingw32/3.4.2/include"  -I"D:/Dev-Cpp/include/c++/3.4.2/backward"  -I"D:/Dev-Cpp/include/c++/3.4.2/mingw32"  -I"D:/Dev-Cpp/include/c++/3.4.2"  -I"D:/Dev-Cpp/include"   

In file included from hello.h:1,
                 from main.cpp:3:
phrase.h:7: error: expected `;' before '(' token

make.exe: *** [main.o] Error 1

Execution terminated
 
Last edited on Sep 7, 2009 at 9:38am
Sep 7, 2009 at 9:49am
#include <string.h>
#include <iostream>

class Phrase {
public:
void phrase(string *p);
};

change to:

#include <string.h>
#include <iostream>
using namespace std
class Phrase {
public:
void phrase(string *p);
};

May be the reason is the compiler can't find the define of class string ,
and this class is in the namespace std.
You should use std namespace
Sep 7, 2009 at 10:00am
Yes, it worked.

But why "using namespace std;" must be declared in phrase.h and not in phrase.cpp?

Thanks,
Sep 7, 2009 at 11:38am
Oh btw, don't include stuff other then the corresponding .h file in .cpp files. And the reason is because the .h can't see anything in the .cpp, so it has no idea what std::string is.
Sep 7, 2009 at 2:53pm
In your header file you should get into the habit of doing

1
2
3
4
class Phrase {
  public:
      void phrase( std::string* p );   // Note use of explicit std:: here.
};


In your .cpp file you can choose between using the explicit std:: everywhere,
putting a "using namespace std;" or putting a "using std::string; /* et al */"
at the top of your file.

Topic archived. No new replies allowed.