Declaration and Definition

The declaration of a class specifies its “shape”, this is what it looks like, often in the .h (interface) file.

The definition of a class is the implementation, where the actual logic is written, in the .cpp file.

// Class declaration; often in .h file 
class Balloon { 
	public: 
		Balloon (); 
		Balloon (string colour); 
		virtual ~Balloon(); 
		void speak() const; 
	private: 
		string colour; 
}; 
 
// Method definitions; often in a different file (.cpp) 
Balloon::Balloon () { // ctors (better way: use initializers) 
	this->colour = "clear"; 
} 
 
Balloon::Balloon (string colour) { // ctor 
	this->colour = colour; 
} 
 
Balloon::~Balloon (){} // dtor 
 
void Balloon::speak() const { 
	cout << "I'm a " << this->colour << " balloon!" << endl; 
}

The teacher seems to declare the variables right below the class definition. This is private by default.

https://www.cs.odu.edu/~zeil/cs333/f13/Public/faq/faq-htmlsu26.html#decldef

Undeclared vs. Undefined Errors

Also see Header File. Look very closely at the error messages. Does it say “undeclared” or “undefined”? These are two very different things, and understanding the difference is the key to fixing the problem.

If the compiler says that a function is undeclared, it means that you tried to use it before presenting its declaration, or forgot to declare it at all.

  • The compiler never complains about definitions, because an apparently missing definition might just be in some other file you are going to compile as part of the program.

However, when you try to produce the executable program by linking all the compiled .o or .obj files produced by the compiler, the linker may complain that a symbol is undefined (none of the compiled files provided a definition) or is multiply defined (you provided two definitions for one name, or somehow compiled the same definition into more than one .o or .obj file).

  • For example, if you forget a function body, the linker will eventually complain that the function is undefined (but the name of the function may be mangled in the error message, see below). If you put a variable or function definition in a .h file and include that file from more than one place, the linker will complain that the name is multiply defined.