Class definition, declaration & access specifiers
class Car1; //declaration
class Car1{//class definition
float speed;
int seats;
int gas;
int cost;
float getSpeed(){return speed;}
void setSpeed(float s){speed=s;}
};
Access specifiers
Within the class body there are sections class members exist in, that represent 3 levels of access restrictions that can be labeled with public, private and protected. This is a very important feature of Object-Oriented Programming and these 3 sections are called the access specifiers.
class Name{
public:
//here exist public members
private:
//here exist private members
protected:
//here exist protected members
}
class Car2{
private:
float speed;
int gas;
public:
float getSpeed(){return speed;}
void setSpeed(float s){speed=s;}
private:
int seats;
public:
int cost;
}
Let’s see how those restrictions impact our use of class members:
int main(){
Car2 c;//creating an object(more about creating objects later)
c.cost=3500;//OK! attribute cost of class Car2 is public
c.speed=15;//NO!! attribute speed of class Car2 is private
c.setSpeed(110);/*OK! method setSpeed() of class Car2 is public and it can access the private
attribute speed */
float k=c.getSpeed();/*OK! method getSpeed() of class Car2 is public and it can access the
private attribute speed*/
int p=c.seats;//NO!! private member
}
Maybe some of you may have noticed, the class Car1 from Example 1 does not have any labeled section but is still legally defined. Now, If we made an object of Class1 and tried to do something with its attributes and methods outside of the class, what would happen? Well there is no explicit restriction so it’s probably okay to access it, right? NO! (!!!) PRIVATE SECTION IS THE DEFAULT SECTION! Meaning, everything in the class that is defined or declared BEFORE the FIRST EXPLICITLY WRITTEN SECTION is considered a private member.
class Car3{//class definition
//private section
float speed;//private memeber
int seats;
public: //now the private section can end
int gas;
int cost;
float getSpeed(){return speed;}
void setSpeed(float s){speed=s;}
}
int main(){
Class3 c3;
c3.speed=100;//NO!!!private member
c3.setSpeed(100); // OK!!
}
Table of contents
- Operator Overloading
- Class Inheritance
- Exceptions
- Namespaces
- Templates
- Standard Library
- Additional Problems