-2

I have created a function within a class. How do I call that function in int main() without declaring any object for the class?

6
  • without creating an object? or without refering the class? Commented 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. Commented Nov 21, 2021 at 15:15
  • stackoverflow.com/questions/20362973/static-functions-in-c maybe what you are looking for. But its not really clear Commented Nov 21, 2021 at 15:21
  • Maybe tell us why you want to do this... Commented 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. Commented Nov 21, 2021 at 16:15

2 Answers 2

1

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; } 
Sign up to request clarification or add additional context in comments.

3 Comments

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.
@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.
Okay..I'll check that out
0

What you can do is to write your function inside the class as static. This lets you call the function without declaring an Object

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.