OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

It is illegal to define a member function within a struct in C++.

MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.

It is illegal to define a member function within a struct in C++. State True or False.

Choose one option.
Show answer & explanation
Answer: B. FALSE (it is completely legal)

In C++, structs and classes are nearly identical except for default access level (public for struct, private for class). Member functions can be defined inside structs just as they can in classes. This has been legal since C++98 and is a fundamental feature of the language.

Step-by-step Derivation:
Example of a legal struct with member functions:

struct Point {
    int x, y;
    
    // Member function inside struct - completely legal
    void display() {
        std::cout << "(" << x << ", " << y << ")";
    }
    
    // Another member function
    int distance() {
        return x * x + y * y;
    }
};

int main() {
    Point p = {3, 4};
    p.display();    // Works fine
    return 0;
}

This code compiles without error in any standard C++ compiler. The statement in option A is false; member functions in structs are not only legal but are a core C++ feature. Option C is incorrect because this behavior is consistent across all compliant C++ compilers.