C++ : How do I call private methods through public ones?
26,093
Solution 1
You already have your class
:
class ClassOne {
private:
void methodOne();
public:
void methodTwo();
};
Implement the functions
of your class
:
void ClassOne::methodOne() { // <-- private
// other code
}
void ClassOne::methodTwo() { // <-- public
// other code
methodOne(); // <-- private function called here
}
Solution 2
The class definition declares the member functions methodOne
and methodTwo
but does not define them. You need to define them out-of-class.
// I assume the return type is void since you omitted it, but
// keep in mind the compiler will not allow you to omit it!
void ClassOne::methodOne() {
// ...
}
void ClassOne::methodTwo() {
// ...
methodOne(); // OK since access is from a member of ClassOne
// ...
}
Author by
Tristran Thorn
Updated on July 09, 2022Comments
-
Tristran Thorn almost 2 years
For our project we are given a code snippet that we should NOT EDIT in any way. We are only allowed to write function definitions for the prototypes in the said snippet.
My problem and question is regarding how I should call the private functions when the code is written this way:
class ClassOne { private: void methodOne(); public: void methodTwo(); };
So I should be able to access methodOne through methodTwo but without writing
{ methodTwo();}
beside methodOne. Help me please?-
aschepler about 9 yearsIf you want one method to call the other, just do so. Or is the question about how to define the methods outside of the class?
-
-
Mooing Duck about 9 yearsYou forgot the return type.
-
The name's Bob. MS Bob. about 9 years@MooingDuck I omitted it because the OP did. But I probably still should put one, huh.
-
Tristran Thorn about 9 yearsHello. I have a follow up question. Since class methods are defined with format returnType className::funcName(<parameter types>), should I omit "className::" when I am writing the definition such that the private function is called from within a public one? Or should I retain it? Thank you in advance :)
-
Jared Burrows about 9 years@DonAbril You never chose an answer for this question yet. One question at a time.
-
Jared Burrows about 9 years@DonAbril The methods in your class,when defined, are in the format:
returnType className::functionName(parameters)
. When we you write the prototypes for them in your class, you just leave them in the format:returnType functionName(parameters)
.