CPP Classes and Member Types

What is a C++ Class?

  • A C++ program will contain a collection of classes, which are written by you, and other classes provided by the standard C++ library.
  • The idea is to create many objects out of the same class and create one or more relation types between these objects.
  • We can say that each class defines the capabilities of a created object.

Create a Class with members

  • You make a new complex type in C++ by creating a class, which is used later to create an object of that type.
  • Here is a list of members that can exist in a C++ class:
    Member How many Description
    Constructors 1..N Method(s) with no return and is executed by the system when an object of the class is created. All Constructors methods must have the same name as the class, but with different number and types of parameters
    Destructor 1 Is a method with no return and is executed by the system when an object of the class is deleted (going out of scope). A Destructor method must have the same name as the class but with a special character ~ in front.
    Member variable 0 ... N Variable(s) you creates to store information about the created object state.
    Method 0 ... N Method(s) you creates to perform operation related to the created object or the object state.
    Static variable 0 ... N Variables you creates to store information related to the class type and is common for all the objects of the class.
    Static Method 0 ... N Methods you creates to perform operations related to the class type and is common for all the objects of the class.

  • It is not required, but it is normal to have to kind of code files:
    1. Header file, that contain constants, declarations of classes and redefined types and have the extension .h (prefered) or .hpp (some developers use other extension as well).
    2. Source file, that contain implementation code for any class declaration done in the header file, and have the extension .cpp (prefered) or .c (some developers use other extension as well).
  • To make a declaration of a class you start with the class statement followed with a name of the class and then two braces {} which inside any member of the class should be declared.
  • A part of th OOP Encapsulation concept;
    • As a rule of design, you should keep the member variables of a class private.
    • To access private data in a class, you should create public functions known as accessor methods.
  • A naming convention has been worked out for variables with accessor methods:
    • The member variable name should always has a first letter in lower case.
      (int age;)
    • A get accessor method for a member variable, should starts with the get verb followed with the member variable name turning the first letter to upper case, have no parameter, and return the same type as the member variable.
      (int getAge();)
    • A set accessor method for a member variable, should starts with the set verb followed with the member variable name turning the first letter to upper case, have a parameter with the same type as the member variable and return void.
      (void setAge(int age);)
    (Remember this is NOT a C++ requirement, but a convention for god programming design.)
    Example of a header file(Car.h) where a Car class is declared:
    // incuding the C++ standard string library
    #include <string>
    
    class Car {
    
    private:
      int age;                            // Member variable
      int weight;                         // Member variable
    
    // The string class is in the standard
    // namespace so you have to use the
    // special notation std:: for namespace selection
      static std::string info;            // Static variable
    
    public:
      static std::string getClassInfo();  // Static method
      Car():age(6),weight(800) { }       // default Constuctor with one parameter
      Car(int Age, int Weight=1000);      // Constuctor with one parameter
      // Destructor is implemented INLINE
      ~Car()                              // Destructor 
      {}                                  // with no code ({}).
      // getAge() is implemented INLINE
     int getAge(){                        // Method which is also
       return age;                        // a get accessor method type
      }
       // getWeight() is implemented INLINE
     int getWeight(){                     // Method which is also
       return weight;                     // a get accessor method type
      }
       // setAge() is implemented INLINE with default value =10
     void setAge(int Age=10){             // Method which is also
        age=Age;                          // a set accessor method type
      }
    };

Declaration

  • All declaration of methods, variables and the class itself must end with a semicolon

Inline methods

  • If you write the implementation of any method directly in the class then the method is a inline method (~Car() and GetAge()) , which involve codes for the method to be included in each object you are creating.
  • Inline methods shall NOT end with a semicolon.

Method Defaults

  • Methods can, as Function also have default values after the same rules as for functions. An example is shown in the Source code above for the setAge method.
  • Default values can be set on all arguments starting from the most right one. As with the constructor above it means default for the age without a default for the weight is not possible.
  • Constructors are invoked in two stages: the initialization stage and the body stage. Member variable can be set in both stages.
  • For the Default Constructor, which have no parameters, in the example above you can see an example of using a initialization stage setup.

Member access specifier

  • Members declared after the private: access statement are all private for any created object and can only be accessed by a created object methods.
  • Members with no prior access statement are also all private.
  • Members declared after the public: access statement are all public for any created object and can be accessed by all of these.

Static Members

  • Static Methods can only access static member variables in a class.
  • All other methods can also access static member variables in a class, but can not be used before you have create an object of the class.
    The Source file(Car.cpp) where the Car class is implemented:
    // ----------------------------------
    // We must include the header file for the Car class
    // as the Compiler must know the declaration of the class.
    #include "Car.h"
    // You include your header file with the file name
    // inside two double-quote as a string notation.
    // ----------------------------------
    
    // A static member variable must be implemented this way:
    // First the type without the static modifier
    // then the class notation Car:: followed by the static valiable name
    // and at last an initial value.
    std::string Car::info = "I am made of steel!";
    
    // Implementation of the static
    // getClassInfo method in Car class
    // The static word shall not be included in the implementation
    std::string Car::getClassInfo() {
      return info;
    }
    
    // Implementation of the 
    // Constructor method in Car class
    Car::Car(int Age, int Weight) {
      age=Age;
      weight=Weight;
    }
  • The compiler has to know which class the implemented method belongs to so you have to denote in front of the method a class notation (Classname::) which in this case will be "Car::" .
    The main file (AppCar.cpp); where we want to use the Car class:
    // ----------------------------------
    #include <iostream>
    // We must include the header file for the Car class
    // as the Compiler must know the declaration of the class.
    #include "Car.h"
    // You include your header file with the file name
    // inside two double-quote as a string notation.
    // ----------------------------------
    
    int main() {
    
    // Create an object instance of the Car  with 
    // the variable name BMW.
    // The (4) tells the compiler to use 
    // the Constructor in Car class  with one integer parameter
    // and default weight
       Car BMW(4);
    
    // Using the getAge() method of the Car
       std::cout << "I am a BMW that is ";
       std::cout  << BMW.getAge() << " year old";
       std::cout  << " and with weight " << BMW.getWeight() << " kilo.\n";
    
    // Using the default Constructor in Car class  with no parameter 
       Car AUDI;
    // Using the setAge() method of the Car
       AUDI.setAge();
       std::cout << "I am a AUDI where age is changed to default ";
       std::cout  << AUDI.getAge() << " years ";
       std::cout  << " and with weight " << AUDI.getWeight() << " kilo.\n";
    
    // Using the static method of the Car class
       std::cout << "I am a Car and ";
    // You can use the Classname:: notation in front of a static method
       std::cout  << Car::getClassInfo() << "\n";
       return 0;
    }
    When we run this application the result will be:
    I am a BMW that is 4 year old and with weight 1000 kilo.
    I am a AUDI where age is changed to default 10 years  and with weight 800 kilo.
    I am a Car and I am made of steel!

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.