3

I have a quick question about class declaration vs. class definition.

So, I can think of four different scenarios of class code:

Which ones qualify as declarations and which as definitions? Why?

TIA.

1)

class foo_empty{};

2,3)

class foo_NoMemDef{
   int f1(); //Member function declaration(?), no body
  //int i; (consider including this as a separate case 3)
};

4)

class foo_final{
   int f2(){}
};
lubgr
  • 37,368
  • 3
  • 66
  • 117
User 10482
  • 855
  • 1
  • 9
  • 22

3 Answers3

6

Which ones qualify as declarations and which as definitions?

All examples show class definitions (that are also declarations). A class declaration that is not a definition looks like this:

class Foo;

Once you "open/close" a class by { and }, you are providing a definition.

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • Well, some definitions are also declarations. – juanchopanza Jun 25 '19 at 13:00
  • @UKMonkey But that is only for the member function `f1`. The class itself is defined. – lubgr Jun 25 '19 at 13:04
  • @lubgr I see what you mean. Thanks! – User 10482 Jun 25 '19 at 22:59
  • @lubgr Can you have a look at the first answer to this question? https://stackoverflow.com/questions/9579930/separating-class-code-into-a-header-and-cpp-file . It says to declare a class in header file but in the code has { } meaning it is a definition right? – User 10482 Jul 05 '19 at 19:26
  • 1
    Yes, I disagree with the wording of this answer. In the header file, it's a class definition (which is also a declaration), while in the implementation file, you have the definitions of the member functions. – lubgr Jul 08 '19 at 07:24
  • Thanks for clearing that up. It had me doubting myself! – User 10482 Jul 09 '19 at 04:14
2

All of your examples are class definitions, as they all finally define the class; you cannot extend the class definition later on any more. Note that providing an implementation for one of the class' methods does not extend the class' interface and hence does not influence the definition of the class itself.

A class declaration introducing a tag "foo" of type "class" would be

class foo;
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

those are all definitions with declarations. a declaration (by itself) in c++ has no {}.

in a header file you might say something like

public class student{

public void UpdateGpa(float grade, int credits);

private float gpa;
private string name;
private int credits;

} 

the above example student is defined and the updategpa function is declared. it would then generally be defined in a cpp file. where it might say

public void UpdateGpa(float grade, int credits){

this.credits+=credits;

gpa= gpa formula

}

this would be the definition of the UpdateGpa Function. things are declared if you cant see the function and know how it works from just what you're seeing. things are defined if there is code provided detailing what the function does.

Sagick
  • 317
  • 2
  • 6
  • 20