Sams Teach Yourself C++ in 21 Days

(singke) #1
Try re-entering Listing 6.8 with these changes:


  • On line 3, change class Pointto struct Point.

  • On line 17, change class Rectangleto struct Rectangle.
    Now run the program again and compare the output. No change should have occurred.
    You’re probably wondering why two keywords do the same thing. This is an accident of
    history. When C++ was developed, it was built as an extension of the C language. C has
    structures, although C structures don’t have class methods. Bjarne Stroustrup, the creator
    of C++, built upon structs, but he changed the name to classto represent the new,
    expanded functionality, and the change in the default visibility of members. This also
    allowed the continued use of a vast library of C functions in C++ programs.


170 Day 6


DOput your class declaration in an .hpp
(header) file and your member functions
in a .cppfile.
DOuse constwhenever you can.

DON’T move on until you understand
classes.

DO DON’T


Summary ..............................................................................................................


Today, you learned how to create new data types using classes. You learned how to
define variables of these new types, which are called objects.
A class can have data members, which are variables of various types, including other
classes. A class can also include member functions—also known as methods. You use
these member functions to manipulate the member data and to perform other services.
Class members, both data and functions, can be public or private. Public members are
accessible to any part of your program. Private members are accessible only to the mem-
ber functions of the class. Members of a class are private by default.
It is good programming practice to isolate the interface, or declaration, of the class in a
header file. You usually do this in a file with an .hppextension and then use it in your
code files (.cpp) using an includestatement. The implementation of the class methods
is written in a file with a .cppextension.
Class constructors can be used to initialize object data members. Class destructors are
executed when an object is destroyed and are often used to free memory and other
resources that might be allocated by methods of the class.
Free download pdf