In C++, a member function with the same name as its class is called a:
2012
In C++, a member function with the same name as its class is called a:
Answer: C. Constructor — ConceptIn C++, special member functions control important stages in an object’s lifetime. A constructor has the same name as its class, has no return type,…
- A.
Inline function
- B.
Friend function
- C.
Constructor
- D.
Static function
Attempted by 2 students.
Show answer & explanation
Correct answer: C
Concept
In C++, special member functions control important stages in an object’s lifetime.
A constructor has the same name as its class, has no return type, and is invoked when an object is created.
Application
Consider the declaration
class Box { public: Box(); };.The member name Box is identical to the class name Box.
Because the declaration has no return type, Box() is the class constructor.
Cross-check and contrast
Inline function: inline describes an optimization-related function specifier; it does not require the function name to equal the class name.
Friend function: friend grants access to non-public members, but the function is not itself a member of the class.
Static function: static makes a member function class-level, but it still has an ordinary function name and a return type.
Therefore, a member function defined with the class name is called a constructor.