Functions and Objects

Class Declaration & Structure in C++

Classes are a blueprint for creating individual objects that contain the general characteristics of a defined object type.


Syntax
class myClass { //class header
public:
    //fields, constructors
    //public method declarations
private:
    //private fields
    //private method declarations
};

Notes

C++ classes themselves do not have a modifier.

There are two access modifiers within the class, which control the access for its corresponding members. Members with 'public' access are directly accessible through an instance of the object. Members with 'private' access can only be accessed within the class itself.


Example
class Bike { 
    public:
    //public fields: 
    int speed; 
    int gear; 
     
    //Constructor: 
    Bike(int startSpeed, int startGear) { 
        gear = startGear; 
        speed = startSpeed; 
    } 
 
    //Methods: 
    void setGear (int newValue) { 
        gear = newValue; 
    } 
     
    void applyBrake(int decrement) { 
        speed -= decrement; 
    } 
    void speedUp(int increment) { 
        speed += increment; 
    } 
}

See Also
Documentation

Classes - C++ Tutorial

Add to Slack

< Do While Loop   |   Constructor >

© 2018 SyntaxDB. All Rights Reserved.