简体   繁体   中英

is it possible to call a method in the base class from a derived class in c++?

The base class is called Tree and it has a private function called insert inside it.

The derived class is called BST and it also has a private function called insert inside it, and I want this insert function to call the insert function inside the Tree class.

is this possible to do in C++ ?

The answer would be 'yes' if the insert method in the base class were public or protected . However, since you said it is private , the answer has to be 'no'.

In a derived class you can call base class functions but only if they are protected or public . private methods can in general only be called by methods of the class itself.

There are however ugly hacks which make it possible to call private functions, see for example here: Calling private method in C++ or here or here . A notable and not too hacky way could be a public member function which returns a pointer to the private function which you want to call.

No, you cannot, unless the base class declares the derived class or its insert() member function to be one of its friend s.

The closest thing to what you want is to declare the base class insert() member function protected , rather than private . This would be simpler and more sensible.

Note that in general it isn't a good idea to give a derived class's member function the same name and signature as a member function in its base class, unless the base class member function is declared virtual and the derived class member function is meant to override it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM