1

In C++ you could do:

class Person{
public:
    int ID;
    char* name;
    void Display(){
        cout << "Person " << name << " ID: " << ID << endl;
    }
}

Where the member function can access other variables in a class, is there anyway to do the same with a struct in C?

3
  • 8
    C has no concept of member functions Commented Jan 6, 2020 at 14:40
  • Well, you could have a pointer to a function as a member of a struct. Commented Jan 6, 2020 at 14:47
  • 4
    C++ provides the (implicit) this pointer to provide access to the members of the instance of the class. You’ll have to simulate that (or, rather, this) in your C code. Commented Jan 6, 2020 at 14:49

2 Answers 2

1

Your C++ code:

class Person {
public:
    int ID;
    char* name;
    void Display() {
        cout << "Person " << name << " ID: " << ID << endl;
    }
}
...
Person person;
...
person.Display();
...

In C there are no member functions, but similar code in C could look like this:

struct Person {
  int ID;
  char* name;
}

void Display(struct Person *this) {
   printf("Person %s ID: %d\n", this->name, this->ID);
}

...
struct Person person;
...
Display(&Person);
...
Sign up to request clarification or add additional context in comments.

1 Comment

I guess a macro that turns foo.bar() into bar(foo) would work
0

c is not a object oriented language, but you can do something like this.

#include<stdio.h>  
#include <string.h>

typedef void (*DoRunTimeChecks)();

struct student  
{  
    char name[20];  
    DoRunTimeChecks func;
};  

void Print(char name[])
{
    printf("Printing student information\n");  
    printf("Name: %s",name);  
}

void main ()  
{  
    struct student s = {"shriram", Print}; 
    s.func = Print;
    s.func(s.name);
}  

1 Comment

Hmm... function pointers in a C struct is not the C equivalence of normal methods, at most virtual methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.