Home > Software engineering >  C method for non class or struct
C method for non class or struct

Time:05-08

Is there any way in C to have a method for variable which is not a class or struct? Suppose I have a defined type dogs for convenience.

using dogs = std::unordered_map<std::string, dog>;
dogs d;

Now, what I want to achieve is to have a method, e.g. print() which operated on the dogs type variable d.

d.print();

CodePudding user response:

Is there any way in C to have a method for variable which is not a class or struct?

You can have free functions which don't require a class. Methods a.k.a. member functions can be defined only for classes.

std::unordered_map<std::string, dog>

std::unordered_map<std::string, dog> is in fact a class. And it has member functions. But you may not define more member functions for this class, nor other classes from the standard library.

You could define a free function such as this:

void print(const std::unordered_map<std::string, dog>&);

Which you can call like this:

print(d);

CodePudding user response:

Your d.print() means invocation of the method print that std::unordered_map<std::string, dog> actually hasn't. You can't add new methods to an existing class in C in contrast to e.g. Python because C is a statically typed language. The only way to add new method to a class is creating a new class that inherits to the interested class like

struct dogs : std::unordered_map<std::string, dog>{
    void print();
};
... // define your dogs::print();

void foo()
{
    dogs d;
    d.print(); //now you can use it
}
  •  Tags:  
  • c
  • Related