Declaration Vs. Definition for classes

Viewed 152

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(){}
};
3 Answers

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.

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;

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.

Related