Object Oriented Programming (Part 2)

I read chapters 2, 14 & 15 from Thinking in C++ second edition Volume 1.  This is a summary of what I read:

 Making and using objects

Separate Compilation:

 

Separate compilation allows the creation of larger programs, since the compiler doesn’t have to build it all at once. Instead, it can separate it in pieces and compile them once at a time (this pieces can be combined, once they are tested and working, into libraries allowing them to be used by other programmers).  A linker program combines the pieces into an executable, and helps with the interaction of functions called between two different pieces.

 

A function is the “smallest” unit of code you must have together in a file (you can’t save the function in separate files). In order for the compiler to be able to use properly functions in other files, you must declare them.

 

Declaration vs Definition:

Declaration says to the compiler, this function looks like this. A definition means that the function or variable should be made in a certain place.

 

Libraries:

 

Use:

"1.       Include library’s header file.

2.       Use functions and variables in it.

3.       Link it to the executable program."

(Thinking in C++ Second Edition Volume I: Introduction to C++, Bruce Eckel)

 

Inheritance and composition:

 

How to choose one over the other? Well, you should choose composition when you want the functions and characteristics “part-of” class inside your class but don’t want its interface to be the same. Basically composition means that the class HAS another class, and inheritance means the class IS another class.

 

Inheritance and composition also reassure, that if you have a bug in your program, and the existing code was proved to work, you know the error is in your code, which makes it easier to find.

Virtual Functions:

 

The redefinition of a virtual function is called overriding. This is done when the base function’s functionality is not specific enough for its children. You write in the child function what you want it to do, disregarding what it states in the base class. This process can be done on more than one level.

i.e.:

 

Animal

Height

Weight

Eat()

Sleep()

Reptile

Height

Weight

Eat()

Sleep()

Mammal

Height

Weight

Eat()

Sleep()

 

 

 

 

 

 

 

 

Cow

Height

Weight

Eat()

Sleep()

Whale

Height

Weight

Eat()

Sleep()

 

 

 

 

 

 

 

 

With the following classes you could say that cow and whale are both child classes from mammal, and that mammal and reptile inherit from animal.

In the example the sleep function can be declared as virtual. Once it is you can override it in both the mammal definition for sleep or in the cow/whale definition, which should be different, but still describe the same action (sleep).

In this example you could also make the animal class abstract. This means that no one will be able to create an object from the class, it will just be used as an interface for “upcasting”.