Skip over navigation

Classes in C++




Problem : Why should you use classes?

Classes are a great way of packaging data and functionality in units that can be easily manipulated. Classes provide structure to C++ programs. If your program does not have classes, you might as well use another language that is not object-oriented!

Problem : How do you call a member function?

To call a member function, specify the object whose function you want to call, and use the dot operator followed by the function name. E.g.: Obj1.func();

Problem : How is private different from public?

Public members of a class are directly accessible from an object by use of the dot operator, whereas private members can only be accessed from within the class itself.

Problem : Why should you use private at all?

Keeping data members private shows good style for encapsulating data by allowing an object to communicate with the rest of the "world" only through its public member functions. Encapsulating data makes it more difficult for a programmer to make an accidental modification of a value.

Problem : What's the point of friend functions?

Friend functions are good for manipulation of objects when it does not make sense to assign the function to a single object. For instance, if a function needed to manipulate the data of two or more objects, a friend function would let the program "see" the parts of the class it would need to.