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

AI Thread Summary
The discussion revolves around a coding issue in C++ related to subclassing and function overriding. The user is trying to call a base class function from a subclass but encounters a compilation error. The error arises from incorrect syntax in the function call. The correct way to call the base class's print function is to use the variable `x` directly, as in `Bear::print(x);`, rather than attempting to declare the parameter type again. This highlights a common mistake among programmers, particularly beginners, in understanding function calls within inheritance. The clarification provided resolves the confusion, emphasizing the importance of proper syntax in function calls.
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:)
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top