Class and Objects in C++ - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Class and Objects in C++

Share This

A class declaration defines a new type that links code and data. This new type is then used to declare objects of that class. Thus, a class is a logical abstraction, but an object has physical existence. In other words, an object is an instance of a class.

By default, functions and data declared within a class are private to that class and may be accessed only by other members of the class. The public access specifier allows functions or data to be accessible to other parts of your program. The protected access specifier is needed only when inheritance is involved (see Chapter 15). Once an access specifier has been used, it remains in effect until either another access specifier is encountered or the end of the class declaration is reached.

You may change access specifications as often as you like within a class declaration. For example, you may switch to public for some declarations and then switch back to private again. The class declaration in the following example illustrates this feature:


#include <iostream> #include <cstring> using namespace std; class employee { char name[80]; // private by default public: void putname(char *n); // these are public void getname(char *n); private: double wage; // now, private again public: void putwage(double w); // back to public double getwage(); }; void employee::putname(char *n) { strcpy(name, n); } void employee::getname(char *n) { strcpy(n, name); } void employee::putwage(double w) { wage = w; } double employee::getwage() { return wage; } int main() { employee ted; char name[80]; ted.putname("Ted Jones"); ted.putwage(75000); ted.getname(name); cout << name << " makes $"; cout << ted.getwage() << " per year."; return 0; }


Happy Exploring!

No comments:

Post a Comment