Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must a method be declared in a C++ class definition?

If only define this method it will have a compiler error.

void classA::testMethod() {    
}

And so it must be declared first:

class classA {    
   void testMethod();
};

Why should these be declared?

I know for common C method methods it is not needed declare, but they can just be defined:

void test() {
}
like image 394
jiafu Avatar asked Sep 26 '14 08:09

jiafu


People also ask

What is declaration and definition in C?

i.e., declaration gives details about the properties of a variable. Whereas, Definition of a variable says where the variable gets stored. i.e., memory for the variable is allocated during the definition of the variable. In C language definition and declaration for a variable takes place at the same time.

Is function declaration necessary in C?

Actually, it is not required that a function be declared before use in C. If it encounters an attempt to call a function, the compiler will assume a variable argument list and that the function returns int.

What is the purpose of class declaration in C++?

A class declaration creates a unique type class name. A class specifier is a type specifier used to declare a class. Once a class specifier has been seen and its members declared, a class is considered to be defined even if the member functions of that class are not yet defined.

What is the difference between declaration and definition of a function?

Definition. Function declaration is a prototype that specifies the function name, return types and parameters without the function body. Function Definition, on the other hand, refers to the actual function that specifies the function name, return types and parameters with the function body.


1 Answers

You don't need to declare the method before you define it, but you need to declare class methods in the class. Else it wouldn't be a class method.

That may seem like a contradiction, but a definition is also a declaration. So what this means is that the definition may appear in the class itself:

class A {
  void testMethod() { /*...*/ } 
};

[edit] Also, practically speaking, inside the class declaration there are private, protected and public parts. This is needed to for encapsulation. If you could declare methods outside the class, you would lose encapsulation. Anybody could access private members merely by defining extra getters and setters, even when those would not make sense. Class invariants would become meaningless.

like image 123
MSalters Avatar answered Oct 21 '22 03:10

MSalters