I have created a function within a class. How do I call that function in int main() without declaring any object for the class?
            Asked
            
        
        
            Active
            
        
            Viewed 346 times
        
    -2
            
            
        - 
                    without creating an object? or without refering the class? – Suraj Rao Nov 21 '21 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 Nov 21 '21 at 15:15
- 
                    https://stackoverflow.com/questions/20362973/static-functions-in-c _maybe_ what you are looking for. But its not really clear – Suraj Rao Nov 21 '21 at 15:21
- 
                    Maybe tell us why you want to do this... – Sean Nov 21 '21 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 Nov 21 '21 at 16:15
- 
                    ... that's a bit of a stupid assignment, because it requires you to write a class where you need no class. Were these assignments maybe written by Java teachers? – Marcus Müller Nov 21 '21 at 18:39
2 Answers
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;
}
 
    
    
        Jason
        
- 36,170
- 5
- 26
- 60
- 
                    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 Nov 21 '21 at 15:58
- 
                    @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. – Jason Nov 21 '21 at 16:03
- 
                    
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
 
    