user.websites.cs2390sum97.lectures.introcplusplus.master
P | N
- Introduction to C++
- Brief History and Overview
- C++ vs. Smalltalk
- Classes and Objects in C++
- Declaring classes
- Data hiding: Public, Private, Protected
- Multiple Inheritance
- Looking up Functions at Run-Time: Virtual
- Slightly More Advanced Topics in C++
- Overloading functions and operators
- Constructors and Destructors
- Class Templates
- Pointers in C/C++
- References in C++
- Brief History
- C was developed in early 1970's by Dennis Ritchie at Bell Labs
- Based on BCPL - Assembler-as-algol
- Used by Ritchie and Ken Thompson for writing and maintaining UNIX
- C++ developed in early 1980's by Bjarne Stroustrup
- C++ is a superset of C
- C programs over about 100,000 lines of code become extremely difficult to read, understand, and maintain
- Goals: Add OOP to C and fix some C shortcomings
- C++ is...
- -Strongly typed: Declare everything, don't mix types
- -Compiled: Faster, smaller, less flexible
- -Mixed object-oriented and procedural: You can cheat
- Your First C++ Program
- #include <iostream.h> // Access the runtime
- main() { // Must be main, not MAIN, not Main
- cout << "The volume of the box car is ";
- cout << 11 * 9 * 40;
- cout << endl;
- }
- Declaring variables
- #include <iostream.h>
- main() {
- int result, height = 11, width = 9;
- int length = 40;
- result = height * width * length;
- cout << "The volume of the box car is"
- << result << endl;
- }
| char | A single character |
| short | A small integer (two bytes) |
| int | Integer of machine's word size |
| long | Large integer (four bytes) |
| float | Floating-point number |
| double | Double-precision floating point number |
| char * | A string (array of characters; array = pointer) |
| void | Typeless (typically, used to declare functions as procedures) |
| type [] | An array (= a pointer) |
Handling input, too
- #include <iostream.h>
- main() {
- int height, width, length;
- cout << "Please type three integers:" << endl;
- cin >> height;
- cin >> width;
- cin >> length;
- cout << "The volume of the box is " <<
- height * width * length << endl;
- }
- {cleon:guzdial:240} g++ input.cc -o input
- {cleon:guzdial:241} input
- Please type three integers:
- 12 456
- 789
- The volume of the box is 4317408
C++ is not Smalltalk
- -Smalltalk is not typed
- -C++ has base types that are not objects, and allows functions that are not methods
- -C++ enforces a difference between an object and a pointer to that object
- -There is no base Object class in C++
- -C++ syntax is more complex than Smalltalk's
- -C++ does not handle memory management
Terminology in C++
| C++ | Smalltalk |
| Class (but classes aren't objects) | Class |
| Class objects or compound objects | Instances |
| Derived class | Subclass |
| Base class | Superclass |
| Member function (sometimes, method) | Method |
| Overloading or Shadowing or Overriding (more ways to do it) | Overriding |
| Member data | Instance variables |
Declaring Classes in C++
- #include <iostream.h>
- #include <string.h>
- class book {
- public:
- book(char *, char *, int);
- void show_book(void);
- private:
- char title[64];
- char author[64];
- int pages;
- };
- class catalog_card : public book {
- public:
- catalog_card(char *, char *, int, char *, int);
- void show_card(void);
- private:
- char catalog[64];
- int checked_out; // 1 if checked out, otherwise 0
- };
Filling in the functions: Constructors
- book::book(char *newtitle, char *newauthor, int newpages)
- {
- strcpy(title,newtitle);
- strcpy(author,newauthor);
- pages = newpages;
- }
- catalog_card::catalog_card(char *title, char *author, int pages, char * newcatalog, int newchecked_out) : book(title, author, pages)
- {
- strcpy(catalog, newcatalog);
- checked_out = newchecked_out;
- }
Filling in the functions: Output
- void book:show_book(void)
- {
- cout << "Title: " << title << endl;
- cout << "Author: " << author << endl;
- cout << "Pages: " << pages << endl;
- }
- void catalog_card::show_card(void)
- {
- show_book();
- cout << "Catalog: " << catalog << endl;
- if (checked_out)
- cout << "Status: Checked out" << endl;
- else
- cout << "Status: Available" << endl;
- }
Using the new classes
- void main(void)
- {
- catalog_card card("Tale of Two Cities","Dickens",1000,"Fiction Row 1",1); // Declaration
- card.show_card();
- }
Data hiding in C++
- public Anyone can access (data or function) through use of the dot (.) operator.
- private No one but the class can access - not even derived classes!
- protected Derived classes and the declaring class can access, but no one else.
Accessing Member Data
- class person_statistics {
- public:
- int month_of_birth;
- int year_of_birth;
- int married;
- void initialize_ssn(char *); // function protoype
- void show_dob(void) { // inline member function
- cout << month_of_birth << "/" << year_of_birth << endl;
- };
- private:
- char ssn[12];
- int children;
- };
- void main(void)
- {
- person_statistics guzdial, ericson;
- guzdial.month_of_birth = 9;
- guzdial.year_of_birth = 62;
- guzdial.married = 1;
- guzdial.children = 1; // DEFECTIVE!!!
- guzdial.show_dob();
- }
Smalltalk Data Hiding in C++ Terms
- -Instance variables are protected (only class and subclasses can access)
- -Smalltalk methods are public (anyone can access)
Multiple Inheritance in C++: Declaring two base classes
- class computer_screen {
- public:
- computer_screen(char *, long, int, int);
- void show_screen(void);
- private:
- char type[32];
- long colors;
- int x_resolution;
- int y_resolution;
- };
- class mother_board {
- public:
- mother_board(int, int, int);
- void show_mother_board(void);
- private:
- int processor;
- int speed;
- int RAM;
- };
Multiple Inheritance in C++: Using both classes in a derived class
- class computer: public computer_screen, public mother_board
- {
- public:
- computer(char *, int, float,
- char*, long, int,
- int, int, int, int);
- void show_computer(void);
- private:
- char name[64];
- int hard_disk; //size of
- float floppy;
- };
Deriving from a Base Class other than Public
- class box{
- public: double height, width, length;
- box() {}; //Default constructor
- box (double h, double w, double l) //with arguments
- {height = h; width = w; length =l;};
- double volume ()
- {return height * width * length;}
- };
- class box_car : public railroad_car, private box {
- public: box_car() : box (10.5, 9.5, 40.0){}; // Default constructor
- }
- -box_car in this example cannot access box private members.
- -box's public and protected members are private within box_car: Accessible, but not public, and even derived classes can't access
Roles for Multiple Inheritance
- Implementation Inheritance
- -Inheriting for functionality but not for semantics
- "Mix-Ins": CLOS, Python.
- -Adding in some additional functionality
Hiding Inherited Classes
| | Public Derivation (e.g., public box) | Protected Derivation (e.g., protected box) | Private Derivation (e.g., private box) |
| Public Member Function | Remains public | Remains protected | Remains private |
| Protected Member Function | Becomes protected | Remains protected | Remains private |
| Private Member Function | Becomes private (to derived) | Becomes private (to derived) | Remains private |
Creating objects at run-time and overriding
First: Let's do it obvious, but wrong
- #include <iostream.h>
- class railroad_car {
- public:
- void display_short_name() {cout << "rrc";}
- };
- class box_car: public raiload_car {
- public:
- void display_short_name() {cout << "box";}
- };
- //..Similar definitions of tank_car, engine, and caboose go here
Main
- //Define raiload car array
- railroad_car *train[100];
- main() {
- int car_count, type_code, n;
- for (car_count = 0; cin >> type_code; ++car_count)
- if (type_code == 0) train[car_count] = new engine;
- else if (type_code == 1) train[car_count] = new box_car;
- else if (type_code == 2) train[car_count] = new tank_car;
- else if (type_code == 3) train[car_count] = new caboose;
- cout << "There are " << car_count
- << " cars in the array." << endl;
- for (n=0; n < car_count; ++n) {
- train[n] -> display_short_name();
- cout << endl;
- }
- }
Running the wrong version
- Input:
- 0 1 1 2 3
- Output:
- There are 5 cars in the array.
- rrc
- rrc
- rrc
- rrc
- rrc
Why didn't each car use its own display_short_name?
- Because C++ can't do the lookup on the fly?
- If it thinks an object is a railroad_car, it thinks it will always call railroad_car functions
- Unless we tell it otherwise...
Fixing the Class Declarations
- #include <iostream.h>
- class railroad_car {
- public:
- virtual void display_short_name() {cout << "rrc";}
- };
- class box_car: public raiload_car {
- public:
- virtual void display_short_name() {cout << "box";}
- };
- //..Similar definitions of tank_car, engine, and caboose go here
- Input:
- 0 1 1 2 3
- Output:
- There are 5 cars in the array.
- eng
- box
- box
- tnk
- cab
If you never expect to use the base function...
- (Sort of like
self error: subclassResponsibility)
- #include <iostream.h>
- class railroad_car {
- public:
- virtual void display_short_name() = 0
- };
- class box_car: public raiload_car {
- public:
- virtual void display_short_name() {cout << "box";}
- };
- //..Similar definitions of tank_car, engine, and caboose go here
Slightly More Advanced Topics in C++
- Overloading functions and operators
- Constructors and Destructors
- Class Templates
- Pointers in C/C++
- References in C++
Overloading Functions in C++
- Multiple signatures can be distinguished if input is distinguishable.
- #include <iostream.h>
- int add_values(int a, int b)
- {
- }
- int add_values(int a, int b, int c)
- {
- }
- void main(void)
- {cout << "200 + 801=" << add_values (200, 801) << endl;
- cout << "100+201+700=" << add_values(100,201,700) << endl;
- }
Overloading operators in C++
- #include <iostream.h>
- #include <string.h>
- class string {
- public:
- string(char *); //Constructor
- void operator +(char *);
- void show_string(void);
- private:
- };
- string::string(char *str)
- {strcpy(data,str);}
- void string::operator +(char *str)
- {strcat(data,str);}
- void string::show_string(void)
- {cout << data << endl;}
- void main(void)
- {
- string title("CS 2390");
- string name("Modeling and Design");
- title.show_string();
- title + name;
- title.show_string();
- }
Constructors and Destructors
- Constructor functions run for each object you create
- -You load up the member data as you want it -- like Smalltalk
initialize:
- -Can have several with different signatures, to initialize in different ways
- Destructor functions run when an object is discarded (explicitly or at end of program)
- -Good time to get rid of connections, free up allocated non-object memory, free-up I/O devices
Class templates: Parameterizing types!
- First Version
- class array{
- public:
- array(int size);
- long sum(void);
- int average_value(void);
- void show_array(void);
- int add_value(int);
- private:
- int *data;
- int size;
- int index;
- };
- long array::sum(void)
- { long sum=0; int i;
- for (i=0; i< index; i++)
- sum = sum + data[i]; //sum += data[i];
- return(sum);
- }
Parameterized Version
- Class T is type of array elements
- Class T1 is type of sum of array elements
- template<class T, class T1>
- class array{
- public:
- array(int size);
- T1 sum(void);
- T average_value(void);
- void show_array(void);
- int add_value(T);
- private:
- T *data;
- int size;
- int index;};
- template<class T, class T1>
- T1 array<T, T1>:sum(void)
- {
- T1 sum = 0; int i;
- for (i = 0; i < index; i++)
- sum += data[i];
- return(sum);}
Pointers in C/C++
- #include <iostream.h>
- void show_string(char *string)
- {
- while (*string != `/0')
- {
- cout << *string;
- string++;
- }
- }
- void main(void)
- {
- show_string("Hello, World!");
- }
- Can also be written:
- while (*string)
- {
- cout << *string;
- string++;
- }
- Or
- even:
- while (*string)
References in C++
- References are not variables: You can't change them, add them, assign a reference to a pointer, etc.
- They're a second name for a variable -- hopefully, a little safer
- Pointer way:
- void swap_values(float *a, float *b)
- {
- float temp;
- temp = *a;
- *a = *b;
- *b = temp;
- }
- C++ references way
- #include <iostream.h>
- void swap_values(float& a, float& b)
- {
- float temp;
- temp = a;
- a = b;
- b = temp;
- }
- void main(void)
- //
- float big = 10000.0;
- float small = 0.00001;
- float& big_alias = big;
- float& small_alias = small;
- swap_valus(big_alias,small_alias);
- // swap_value(float& big, float& small);
- cout << "Big:"<<big<<endl;
- cout << "Small:"<<small<<endl;
- }
Previous | Next
Last modified at 8/5/97; 1:32:44 PM
Other Links of Interest
College of Computing | EduTech Institute | GVU Center
Mark Guzdial | Papers | CS 2390 Spring '97 Home Page | STABLE | MMC-CaMILE
Slide Master