I have created a function within a class. How do I call that function in int main() without declaring any object for the class?
- without creating an object? or without refering the class?Suraj Rao– Suraj Rao2021-11-21 15:14:40 +00:00Commented Nov 21, 2021 at 15:14
- not clear what you mean (you're abusing vocabulary a bit, so we can't tell); probably you want to do something that makes no sense! Please give us a minimal, but compiling, example of what you mean.Marcus Müller– Marcus Müller2021-11-21 15:15:01 +00:00Commented Nov 21, 2021 at 15:15
- stackoverflow.com/questions/20362973/static-functions-in-c maybe what you are looking for. But its not really clearSuraj Rao– Suraj Rao2021-11-21 15:21:17 +00:00Commented Nov 21, 2021 at 15:21
- Maybe tell us why you want to do this...Sean– Sean2021-11-21 16:10:20 +00:00Commented Nov 21, 2021 at 16:10
- Basically this is the problem- Print the average of three numbers entered by the user by creating a class named 'Average' having a function to calculate and print the average without creating any object of the Average class.noob– noob2021-11-21 16:15:10 +00:00Commented Nov 21, 2021 at 16:15
| Show 1 more comment
2 Answers
You can do it by using a static member function as shown below:
#include <iostream> class NAME { public: //define a static member function static void print_st() { std::cout<<"static print_st callled"<<std::endl; } }; int main() { //call static member function without using an object NAME::print_st(); return 0; } 3 Comments
noob
sorry for describing it incorrectly at first... I know how to call a function using an object of the class but I wanted to know how can i do the same thing without object declaration.
Richard
@noob You can do it for a static member function as shown in my edited answer/code. I have added it in my answer. Check it out.
noob
Okay..I'll check that out