Problem with inheritance in C++

Feb 4, 2010 at 11:59pm
Here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
//gradedactivity.h 
class gradedactivity 
{
 public:
  char letter;
  void func();
  char getLetter()
    {
      return letter;
    }

};

1
2
3
4
5
6
7
8
9
10
//gradedactivity.cpp
#include "gradedactivity.h"
#include <iostream>
using namespace std;

void gradedactivity::func()
{
  cout << "This is func function of gradedactivity" <<endl;
  
}


1
2
3
4
5
6
7
8
9
10
//passfailactivity.h
#include "gradedactivity.h"
class passfailactivity : public gradedactivity {
 public:
  float passingscore;
  void func(int);
  void msg();
  
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//passfailactivity.cpp

#include "passfailactivity.h"
#include <iostream>
using namespace std;
void passfailactivity::msg()

{


  cout << "In msg of passfailactivity" <<endl;


}


void passfailactivity::func(int j)
{
cout << "This is func function of passfailactivity" <<endl;

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//prog.cpp
#include "passfailactivity.h"
#include <iostream>
using namespace std;

int main()
{
  passfailactivity e;

  e.msg();

    e.func(6);
    e.func();
  return 0;
}


I get this result on Linux:

webdev:~/cppcode$ g++ -c passfailactivity.cpp
webdev:~/cppcode$ g++ -c gradedactivity.cpp
webdev:~/cppcode$ g++ -c prog.cpp
prog.cpp: In function `int main()':
prog.cpp:12: no matching function for call to `passfailactivity::func()'
passfailactivity.h:5: candidates are: void passfailactivity::func(int)
webdev:~/cppcode$

My question is isn't void func() inherited by passfailactivity ? Why do I get this error ?
Any help would be welcome.
Thanks!
Feb 5, 2010 at 12:06am
That is because the function is being "hidden". Read this for information:

http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9
Feb 5, 2010 at 12:29am
Thanks a lot !!
Looks like, coming in from the Java world, I am in for quite a lot of surprise !!

In java this kind of thing would be perfectly acceptable and would run just fine with no "using" like declarations in the derived class !

And also , in Java , hiding applies to static methods (not sure how C++ handles static methods with same signature in base and derived classes) and fields.
Feb 5, 2010 at 2:57am
Probably hides them too. If you want to do something like overloading through classes like you seem to, you would have to use virtual functions.
Feb 5, 2010 at 3:11pm
Right and if you consciously want to call base func() then easy way is to redefine base method in derived class by:
1) simply call base method using scope resolution operator => gradedactivity::func();
2) or simply __super::func(); //super is a keyword (this will also work for multi-level inheritance)
Feb 5, 2010 at 6:46pm
__super keyword is Microsoft specific.
Topic archived. No new replies allowed.