Learn C++ - C++ Class






C++ keyword class identifies the code as defining the design of a class.

The syntax identifies Product as the type name for this new class.

The first step to design a class is to provide a class declaration.

Syntax

The class declaration is coded after a declaration and can include data members and function members.

The declaration has a private section, and members declared in that section can be accessed only through the member functions.

The declaration also has a public section, and members declared there can be accessed directly by a program using class objects.

Typically, data members go into the private section and member functions go into the public section.

A typical class declaration has this form.


class className { 
private: 
     data member declarations 
public: 
     member function prototypes 
}; 

The contents of the public section constitute the abstract part of the design, the public interface.

Encapsulating data in the private section protects the integrity of the data and is called data hiding.

The second step in a class design is to implement the class member functions.

The following code shows how to define a Class with a Member Function.


#include <iostream> 
using namespace std; 
//from w  w  w.j  av a2 s .c  o  m
class Printer { 
public: 
    // function that displays a welcome message to the Printer user 
    void displayMessage() { 
        cout << "Welcome to the Grade Book!" << endl; 
    }
};
int main() 
 { 
    Printer myPrinter; // create a Printer object named myPrinter 
    myPrinter.displayMessage(); // call object's displayMessage function 
}

The code above generates the following result.





Member Function with a Parameter

The following code shows how to Define class Printer with a member function that takes a parameter, create a Printer object and call its displayMessage function.


#include <iostream> 
#include <string>
using namespace std; 
// w w w .  j  av a  2  s.co  m
class Printer { 
public: 
   void displayMessage( string courseName ) 
    { 
       cout << "Welcome to the grade book for\n" << courseName << "!" 
           << endl; 
    }
};

// function main begins program execution 
int main() 
{ 
    string nameOfCourse; // string of characters to store the course name 
    Printer myPrinter; // create a Printer object named myPrinter 

    cout << "Please enter the course name:" << endl; 
    getline( cin, nameOfCourse ); // read a course name with blanks 
    cout << endl; // output a blank line 

    myPrinter.displayMessage( nameOfCourse ); 
}

The code above generates the following result.





set Functions and get Functions

Define class Course that contains a courseName data member and member functions to set and get its value ;

Create and manipulate a Course object with these functions.


#include <iostream> 
#include <string> // program uses C++ standard string class 
using namespace std; 
/* ww w .  jav  a  2 s.co  m*/
class Course { 
public: 
    void setCourseName( string name ) { 
        courseName = name; // store the course name in the object 
    }

    string getCourseName() { 
        return courseName; // return the object's courseName 
    }

    void displayMessage() { 
        cout << "Welcome to the grade book for\n" << getCourseName() << "!" 
           << endl; 
    }
private: 
    string courseName; // course name for this Course 
};

int main() { 
    string nameOfCourse; // string of characters to store the course name 
    Course myCourse; // create a Course object named myCourse 

    cout << "Initial course name is: " << myCourse.getCourseName() 
        << endl; 

    cout << "\nPlease enter the course name:" << endl; 
    getline( cin, nameOfCourse ); // read a course name with blanks 
    myCourse.setCourseName( nameOfCourse ); // set the course name 

    cout << endl; // outputs a blank line 
    myCourse.displayMessage(); // display message with new course name 
}

The code above generates the following result.

Example

This declaration enables you to declare variables, called objects, or instances, of the Product type.

#include <string> 
class Product  { 
    private: 
         std::string company; 
         long shares; 
         double normal_val; 
         double discount_val; 
         void set_tot() { discount_val = shares * normal_val; } 
    public: 
         void acquire(const std::string & co, long n, double pr); 
         void buy(long num, double price); 
         void sell(long num, double price); 
         void update(double price); 
         void show(); 
};

For example, the following declarations create two Product objects called computer and toy:

Product computer; 
Product toy; 

The information you decided to store are in class data members, such as company and shares.

The company member of computer, for example, holds the name of the company, the share member holds the number of shares Sally owns.

Access Control

private and public labels describe access control for class members.

Any program that uses an object of a particular class can access the public portions directly.

A program can access the private members of an object only by using the public member functions.

For example, the only way to alter the shares member of the Product class is to use one of the Product member functions.

The public member functions act as agents between a program and an object's private members.

This insulation of data from direct access by a program is called data hiding.

A class design attempts to separate the public interface from the specifics of the implementation.

Class Member Functions

The following code shows how to implement the Product class.


#include <iostream> 
#include <string> 
//w w w .j  av a  2s . co  m
class Product  // class declaration 
{ 
          private: 
               std::string company; 
               long shares; 
               double normal_val; 
               double discount_val; 
               void set_tot() { discount_val = shares * normal_val; } 
          public: 
               void acquire(const std::string & co, long n, double pr); 
               void buy(long num, double price); 
               void sell(long num, double price); 
               void update(double price); 
               void show(); 
};
void Product::acquire(const std::string & co, long n, double pr) { 
     company = co; 
     if (n < 0) 
     { 
         std::cout << "Number of shares can't be negative; " 
                    << company << " shares set to 0.\n"; 
         shares = 0; 
     } 
     else 
         shares = n; 
     normal_val = pr; 
     set_tot(); 
} 

void Product::buy(long num, double price) 
{ 
         shares += num; 
         normal_val = price; 
         set_tot(); 
} 

void Product::sell(long num, double price) 
{ 
     using std::cout; 
         shares -= num; 
         normal_val = price; 
         set_tot(); 
} 

void Product::update(double price) 
{ 
     normal_val = price; 
     set_tot(); 
} 

void Product::show() 
{ 
     std::cout << "Company: " << company 
                << "  Shares: " << shares << '\n' 
                << "  Share Price: $" << normal_val 
                << "  Total Worth: $" << discount_val << '\n'; 
} 

#include <iostream> 
int main(){ 
     Product computer; 
     computer.acquire("NanoSmart", 20, 12.50); 
     computer.show(); 
     computer.buy(15, 18.125); 
     computer.show(); 
     computer.sell(400, 20.00); 
     computer.show(); 
     computer.buy(300000,40.125); 
     computer.show(); 
     computer.sell(300000,0.125); 
     computer.show(); 
     return 0; 
} 

The code above generates the following result.

Inline Methods

You can define a member function outside the class declaration and still make it inline.

To do so, you just use the inline qualifier when you define the function in the class implementation section:

class Product 
{ 
private: 
     ... 
     void set_tot();  // definition kept separate 
public: 
     ... 
}; 

inline void Product::set_tot()  // use inline in definition 
{ 
     discount_val = shares * normal_val; 
}