How could I call a base class virtual function from the derived class ? (C++)

Click For Summary
SUMMARY

The discussion centers on calling a base class's virtual function from a derived class in C++. The user encountered a compilation error while trying to invoke the base class's `print` function from the `Panda` subclass. The correct syntax for calling the base class function is `Bear::print(x);` instead of `Bear::print(char x);`. This highlights the importance of using the correct variable name rather than redeclaring the parameter type in the function call.

PREREQUISITES
  • Understanding of C++ class inheritance
  • Familiarity with virtual functions in C++
  • Knowledge of function overloading and parameter passing
  • Experience with DEV-CPP IDE for C++ development
NEXT STEPS
  • Review C++ class inheritance and polymorphism concepts
  • Learn about virtual function implementation and overriding in C++
  • Explore common compilation errors in C++ and their resolutions
  • Practice debugging techniques in DEV-CPP to resolve similar issues
USEFUL FOR

C++ developers, software engineers, and students learning object-oriented programming who want to understand class inheritance and virtual function usage.

walnutTree
Messages
5
Reaction score
0
Dear All,
I have got a subclass (Panda), which inherits a Print function from the base class (Bear).
I'd like to be able to call the base class's function from the subclass.
But my complier gives me the following error message:

In member function `virtual void Panda::print(char)':
expected primary-expression before "char"


I use DEV-CPP.
Heres is my code causing the problem:

Code:
class Bear{
      public:
             virtual void print(char x)
             {
                 std::cout<<"bear"<<std::endl; 
             }
      };
class Panda : public Bear{
    public:
             void print(char x)
             {
                Bear::print(char x);
                std::cout<<"panda"<<std::endl;  
             }  
      };

Could you tell me what's the wrong?
Any ideas would be appreciated!
 
Technology news on Phys.org
Look very closely at this line:
walnutTree said:
Code:
                Bear::print(char x);
It's a function call, so more like this:
Code:
                Bear::print(x);
If you're like me, you've slapped yourself in the forehead and groaned by now. :wink:
 
thanks for clearing things up, it was a rookie mistake...
and the slapping took place as well:)
 

Similar threads

  • · Replies 36 ·
2
Replies
36
Views
6K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 6 ·
Replies
6
Views
12K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 3 ·
Replies
3
Views
4K
Replies
6
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 89 ·
3
Replies
89
Views
6K
Replies
10
Views
2K