-2

Is it possible to implement dot notation in C (OOP) a la Python?

Something like:

struct myClass {
    ...
    ...
}

And then have a method on that struct like:

myClass.someMethod();
Jasonca1
  • 4,848
  • 6
  • 25
  • 42
  • 2
    Do you mean a [static member](https://www.tutorialspoint.com/cplusplus/cpp_static_members.htm)? Dot notation is for instances of a class/struct. – Luke Ramsden May 16 '18 at 14:36
  • 1
    A struct with pointers to functions? – Jose May 16 '18 at 14:37
  • Well just methods attached to structs, which I assume are the closest you can get to classes in C – Jasonca1 May 16 '18 at 14:38
  • 2
    @Jasonca1 Luke is asking whether you really meant `myClass.someMethod();` or rather `myClass myInstance; myInstance.someMethod();`. – sepp2k May 16 '18 at 14:39
  • you can somewhat kludge it (e.g. instance specific methods, which can be done in C *kinda*) you are responsible for passing on the value of the the member back to the functions. – Ahmed Masud May 16 '18 at 14:40
  • 1
    I believe that's what C++ is for :) –  May 16 '18 at 14:42
  • You can use function pointers but often it is better to use specially named (prefixed) functions and treat/document those as if they were member functions. – Lundin May 16 '18 at 14:42
  • @Orangesandlemons Nah, C++ is for creating a poodle out of a feather, when all you wanted was to avoid creating a hen out of a feather. – Lundin May 16 '18 at 14:44
  • @sepp2k Both. Being able to implement static methods and member methods. – Jasonca1 May 16 '18 at 14:46
  • @Jasonca1 `typename.id` is not valid syntax in C, nor is `typename::id` (which is how you'd access static members in C++), so no, there's no way to make that work. – sepp2k May 16 '18 at 14:50

1 Answers1

0

Yes, someMethod() will be a function pointer:

#include <stdio.h>

typedef struct
{
    void (*someMethod) (void);

}Test;

void asd (void)
{
    printf("works");
}

int main(void)
{
    Test test;
    test.someMethod = asd;
    test.someMethod(); // will print works
}
Martin Chekurov
  • 733
  • 4
  • 15