Skip to content

Posts from the ‘C and C++ Tutorials’ Category

10
Jul

Quick Guide to Object Oriented Programming in C++ (Part 2)

This is a second part from a quick guide to Object Oriented Programming in C++ (aka OOP). We want this guide to be a very practical intro to Object Oriented Programming in C++.

In this tutorial we will write some examples that describe make use of encapsulation, inheritance. and polymorphism

1. Encapsulation

Encapsulation is the process of hiding implementation informations of a class or function so that only needed information will be available to the user of the class. This way we protect the the class/library against directly accessing/modifying values of some variables of the class for example that should have some values only. For example if we have a variable in a class that keep Score and we do not want the minimum and maximum score to be in a range we can hide that variable and only allow Setters and Getters functions to access it. A Setter function is a member function of that class that we will define, it’s a function that have access to that variable and set the value for that variable. We cannot access that variable directly but that member function can. And that Setter function (we call it Setter function because it sets a value for that variable) will know to set score within a range and will take care of wrong values added by user of the class.
Read more »

7
Jun

Quick Guide to Object Oriented Programming in C++ (Part 1)

This is a quick guide to Object Oriented Programming in C++ (aka OOP). Which even if not exhaustive, we want it to be a very practical guide to Object Oriented Programming in C++.

1. Defining a Class in C++ (Example 1)

Starting to learn programming in C++ let’s see some examples. Next is a simple example how to define a C++ Class. There are three files: the header file for the class, the implementation file for the class and main program that make use of the class.

#ifndef SCORE_H
#define SCORE_H
// Score.h --- header file for Score class
 
#include <string>
 
using namespace std;
 
class Score {
    public:
        // class constructor
        Score();
 
        // class destructor
        ~Score();
 
        void SetPlayerName(string playerName);
        string GetPlayerName();
 
        void SetPlayerId(int plId);
        int GetPlayerId();
 
        void SetScore(int sc);
        int GetScore();
 
    private:
        string playerName;
        int playerId;
        int score;
};
 
#endif
</string>

By looking at the header file with definition of the class (Score.h) we notice we’ve defined variables (also called class variables or properties in some programming languages) and function members (also called methods in some languages like Java).

Read more »