Previous: Preprocessor Up: C++ basics Next: Inheritance

This is an automatically generated documentation by LaTeX2HTML utility. In case of any issue, please, contact us at info@cfdsupport.com.


C++ classes are collections of data of different type and functions (called member data and member functions), that can act on that data. They are used to wrap related data to one object to allow the better readability of the code and the more intuitive representation of real word data. One can see an example of the C++ class in training/cpp_tutorial in directory class in file main.cpp:


class animal

    std::string color_;

    int numberOfLegs_;


    // constructor
    // initialises data
    animal(std::string color, int numberOfLegs )

    // get number of legs of the animal
    int numberOfLegs() const {return numberOfLegs_;}

    // get animal color
    std::string color() const {return color_;}

int main()
    animal parrot = animal("blue with stripes", 2);

    std::cout << "Our parrot is " << parrot.color() << " and has " << parrot.numberOfLegs() << " legs.\n";

    return 0;

The class animal is defined in the code. It has a member data of a type int and string for representing animals’ color and their number of legs. It has three functions. The first is a constructor, the function with a special purpose of initializing of the class. The constructor has no return a type and always has the same name as the class. The other two functions are for an access to the class data. Note, that they are written in a way, that cannot change the data, only get their values. In the function main on the line 34, one instance of the class is used to represent a parrot (one particular instance of a class is called object). During instantiating of the parrot object, constructor is called and member data are set. Then, on the line 36, both functions for access to data are used. The file can be compiled and ran using following command:

# g++ main.cpp -o animal


# x86_64w64-mingw32-g++ main.cpp -o animal

Running the program should yield following command:

# ./animal
# Our parrot is blue with stripes and has 2 legs.

A less trivial example – OpenFOAM has a class volScalarField. One instance of that class (one specific instance of a class is called object) can be used to represent e.g. pressure field. This object contains values of an internal field, boundary conditions, a name of the field etc. conveniently packed into one object. It has also its own functions, that make easy e.g. to set or get dimensions of that field, write the whole field into a file (such as 0/p) or calculate an average without having the direct access to the data stored inside the class.

Previous: Preprocessor Up: C++ basics Next: Inheritance