Introduction to C++ Classes

Note: Some of the slides-contents below are repeated from Introduction to C++

C++ Classes

  • Covered in Section 1.5, 1.6, 2.8
  • We will do parts of section 2.8 first

C++ class

  • C++ allows programmers (us) to define our own types (in addition to built-in types like int)
  • These types are known as classes
  • Variables can be defined for these classes just like variables for built-in data types like int

Variable/Object

  • int v1;
    • v1 is a variable of type int
    • v1 is an object of type int

Sales_item class

  • Provides the following operations:
  • >> input operator to read a Sales_item object
  • << output operator to write a Sales_item object
  • + addition operator to add two Sales_item objects
  • = assignment operator to assign one Sales_item object to another
  • same_isbn() member function

Sales_item class – 2

  • These operations/functions of Sales_item are defined elsewhere and accessible to us using header file Sales_item.h
  • Sales_item book;
    • See 1/item_io.cc
    • book is a variable of type Sales_item
    • book is an object of type Sales_item
    • book is an object of class Sales_item (common usage)

Sales_item

  • Multiple objects can be defined of Sales_item
  • Sales_item item1, item2, item3;
    • 3 Sales_item objects have been created
    • Each object will have its own data
    • Similar to multiple variables/objects of built-in types.

struct vs class

  • C++ class has all functionality of ‘C’ struct
  • And has more functionality than struct
  • Note that struct is supported in C++ also and further note that C++ struct is more powerful that C struct.

Type Safety

  • C and C++ are type-safe languages
  • Compiler knows data type of variables/objects and disallows inappropriate operations
    • E.g. Passing a character pointer where a float argument is expected
  • Type-safe languages force some amount of discipline on the programmer (otherwise – lots of compiler error and warning messages).

Object jargon

  • Sales_item item;
  • Based on the above code the following jargon can be used:
    • item is an object of type Sales_item
    • item is a Sales_item object
    • item is a Sales_item
  • This is similar to jargon used for variables/objects of built-in types

Member Functions

  • See add_item2.cc in folder 1
  • A member function is a function defined (provided) by a class
  • Member functions a.k.a. Methods
  • Dot operator used to invoke member function in the context of an object
  • item1.same_isbn(item2)
  • same_isbn() method of item1 is called.

Addition operator

  • Adding two Sales_item objects creates a new Sales_item object whose:
    • ISBN is that of the operands
    • Number sold and revenue reflects the sum of the corresponding values of the operands
    • For input: [ISBN, no. sold, price of each]
      • 0-201-78345 3 20.00
      • 0-201-78345 2 25.00
    • Output is: [ISBN, no. sold, total revenue, average price]
      • 0-201-78345 5 110 22

Running add_item2.exe

  • Build programs in folder 1 by using command make
  • Run add_item2.exe by:
    • $ ./add_item2.exe
    • Will prompt you for Sales_item data (ISBN, no. sold and price of each)
    • Will print out sum

Running add_item2.exe – 2

  • You can run programs which use standard input (cin) against a data file by redirection
  • Data file for add_item2.exe is data/add_item2
  • ./add_item2.exe < data/add_item2
    • Runs add_item2.exe with input taken from file data/add_item2

Redirecting output

  • ./add_item2.exe < data/add_item2 > data/xyzsum
    • Also redirects output to file data/xyzsum
    • Be careful to choose file names different from that already in data
  • Can copy folder 1 to a working directory and safely experiment
    • cp –R src-folder dest-folder
      • Command for recursive (folders and contained sub-folders) copy

Linux User Level Knowledge

  • What are the commonly used Linux text based commands?
  • How to become a power user?
  • What are the commonly used GUI programs on Linux?
  • Check out the Internet for the above

Exercises

  • Copy folder 1 to a working directory
  • ‘make’ the executables in that directory
  • Run program add_item2 with keyboard data and file data
  • Save output of program into a data file and view it.
  • Read add_item2.cc and understand it
  • Go through Linux reference guides for newbies

Think About – Exercise

  • Exercise 1.24 (Section 1.5.2)
  • Program reads several transactions
  • For each new transaction determine if it is the same ISBN as previous transaction
  • Keep a count of how many transactions there are for each ISBN
  • Test program with test data (file)
  • Test data should have multiple transactions with transactions for same ISBN grouped together

Exercise 1.24 & Assignment

  • See avg_price.cc
  • Assignment: Modify avg_price.cc to print individual transactions followed by total sales info (total sales info is as is already given by avg_price.cc)
  • Test your solution with existing data (data/book_sales).
  • If there are bugs in your program mention it as comments in your source code.

Read Course Book

  • Chapters 1 and 2 of course book have been covered (barring few exceptions)
  • Please read chapters 1 and 2 of course book

——–

Note: The course book is C++ Primer, 4th Edition by Lippman, Lajoie and Moo. References above to source files, and use of code within those files, are of example code given in and/or along with the book. As this post is freely accessible on the Internet, not-for-profit, and for educational purposes, based on the permission related statements in the source code, I have considered that permission has been granted to use them here.

Advertisements

Introduction

Why Learn C++?

  • Very powerful and respected prog. Lang.
  • Highly respected in Academia
  • B. Tech./M.Tech. Project work
  • Job Written Test + Interview
  • Research: Programming work can be done in C++

Only course in C++

  • This may be the only course in C++ done by you.
  • So learn it well
  • Benefits, later on in life, can be enormous
  • Excellent Lab facilities
  • Use extra Lab time whenever possible
  • But do not neglect other courses

Course Book

  • C++ Primer, Fourth Edition
  • Authors:
    • Stanley B. Lippman
    • Josee Lajoie
    • Barbara E. Moo
  • Publisher: Pearson Education
  • ISBN: 81-317-1077-7
  • Price
    • List Price: Rs. 475
    • Discount: Usually 10 to 20%

Course Book – 2

  • Availability of hard copy enables:
    • Easy lookup and study
    • Faster and better learning
  • At least one copy for two students is essential
  • Will be useful after course too
  • Procure book quickly
  • Book covers both C and C++
  • Reading chapters of book will be very useful

First C++ Program

  • #include   <iostream>  //Not iostream.h
  • int main()
  • {
    • std::cout  <<  “Hello world\n”;
  • }

First C++ Program – 2

  • C++ is a superset of C
  • Standard header files do not have .h typically
  • The iostream header includes information about stream objects used for input and output.
  • All such stream objects are said to be part of the iostream library
  • Instead of printf we use std::cout

First C++ Program – 3

  • std is a namespace
  • cout is an object which writes (outputs) to a stream (the terminal usually)
  • :: is required between namespace and object
  • << is the way to direct data into cout object
  • << is also called output operator

First C++ Program – 4

  • Source code file extension should be .cpp
  • Save file as firstpgm.cpp
  • Compile using c++ or g++
  • Executable file is named as a.out

Second C++ Program

Second C++ Program – 2

  • << output operator can be used multiple times in one statement
  • std::endl is another way of inserting a newline (\n)
  • Defining int variables is same as C

Second C++ Program – 3

  • std::cin is an input stream object which usually reads from keyboard
  • >> is the input operator which reads input and puts the input into variables on right  hand side of operator

Read Course Book

  • Course book (C++ Primer 4/e):
  • Gives a lot of additional information far beyond what we have time to cover in class
  • Is somewhat precise and so may take getting used to

Read Course Book – 2

  • But it is very good and very accurate
  • Has simple exercises
  • Has nice layout with certain paragraphs marked specially as Notes or Beware (warnings)
  • Reading and understanding it thoroughly will make you a thorough C++ Guru

Hands On (Finally :-))

  • Start your system
  • Choose Red Hat Linux as OS (instead of default Windows)
  • Log on with userid: — and password: —
  • Wait for the GUI (Graphical User Interface) to come up properly
  • Open a terminal window

First Assignment

  • Write the Hello World program using vi
  • Source file name must end in .cpp
  • Compile it using c++ or g++
  • Executable file will be a.out (like what cc does)
  • Run ./a.out

Second Assignment

  • First copy the book code zip file onto your system
  • Unzip the file
  • Now read 1/add.cc
  • Then write a program which takes in four integral numbers and gives the average of them as output.

Introduction – 2

End of Input

  • See 1/mysum.cc (Section 1.44 in book)
  • Use Ctrl-D to signify End of data from Keyboard
  • while (std::cin >> value)
    • Operation is executed
    • std::cin is evaluated (true/false)
    • If operation succeeded cin is true
    • If operation failed (invalid input, end of data) cin becomes invalid and returns false

Sales_item class

  • Chapter 1 of Course Book introduces this class
  • I prefer to skip classes (C++ classes :-)) till later

Chapter 2

  • Variables and Basic Types
  • Built-In types: int, char, long, float, double etc.
  • Literals: 128, 3.14f, ‘a’, “Rama”
  • Variables: int a = 2;
  • variable vs. object: For now we can use the word interchangeably

const object/variable

  • const int bufsize = 512;
  • Value cannot be changed

Temporarily skipping

  • References (Sec. 2.5)
  • Typedefs (Sec 2.6)
  • Enums (Sec 2.7)
  • Will cover them later

C++ Classes

  • Covered in Section 1.5, 1.6, 2.8
  • We will do parts of section 2.8 first

C++ class

  • C++ allows programmers (us) to define our own types (in addition to built-in types like int)
  • These types are known as classes
  • Variables can be defined for these classes just like variables for built-in data types like int

Variable/Object

  • int v1;
    • v1 is a variable of type int
    • v1 is an object of type int

Sales_item class

  • Sales_item book;
    • We assume Sales_item is defined elsewhere and accessible to us using header file Sales_item.h
    • See 1/item_io.cc
    • book is a variable of type Sales_item
    • book is an object of type Sales_item
    • book is an object of class Sales_item (common usage)

Sales_item

  • Multiple objects can be defined of Sales_item
  • Sales_item item1, item2, item3;
    • 3 Sales_item objects have been created
    • Each object will have its own data
    • Similar to multiple variables/objects of built-in types.

struct vs class

  • C++ class has all functionality of ‘C’ struct
  • And has more functionality than struct
  • Note that struct is supported in C++ also and further note that C++ struct is more powerful that C struct.

Type Safety

  • C and C++ are type-safe languages
  • Compiler knows data type of variables/objects and disallows inappropriate operations
    • E.g. Passing a character pointer where a float argument is expected
  • Type-safe languages force some amount of discipline on the programmer (otherwise – lots of compiler error and warning messages).

Object jargon

  • Sales_item item;
  • Based on the above code the following jargon can be used:
    • item is an object of type Sales_item
    • item is a Sales_item object
    • item is a Sales_item
  • This is similar to jargon used for variables/objects of built-in types

Introduction – 3

References

  • Section 2.5 in course book
  • A reference serves as an alternative name for an object
  • In real-world programs, references are primarily used as parameters to functions
  • Reference is different from pointer
  • Defined by preceding a variable name by the & symbol

Reference Example

  • int ival = 1024;
  • int &refval = ival;
  • refval is a reference to ival
  • refval += 2; // adds 2 to ival
  • int i1 = refval; // assigns value of ival to i1

Reference examples

  • A reference MUST be initialized.
  • int &refval2; //error
  • A reference must be initialized using an object of the same type as the reference
  • int &refval3 = 10; // error – initializer must be an object

Reference vs pointer

  • Pointer uses indirection syntax
  • int *iptr = &ival;
  • *iptr = 5;
  • Note that & symbol is used both for references and addresses; From context we know whether it is a reference or an address.

Reference vs pointer – 2

  • Pointer is a separate variable whose value can be independently changed. Reference is only an alias to an object and does not have a separate existence
  • iptr = null;
  • Pointer can be changed to point to another object
  • Reference can never be changed to become an alias for another object

Const references

  • A const reference is a reference that refers to a const object (or literal value)
  • const int ival = 1024;
  • const int &refval = ival; //ok
  • int &ref2 = ival; // error: nonconst reference to a const object
  • const int &r = 42; //ok as it is a const reference

Exercise

  • Solve Exercises section 2.5 from course book. Write observations/answers in a text file
  • Write a program that:
    • Defines double variables
    • Defines non-const and const references to them
    • Defines pointers to them
    • Then write code which uses the references and pointers – objective of the code is to promote your understanding of references.

Typedef

  • A typedef defines a synonym for a type
  • typedef double wages;
  • wages hourly, weekly;
  • typedef struct { … } abc;
  • abc var1;

Enumerations

  • File open mode typically may be one of three values: input, output or append
  • To keep track of openmode we could use three integer constants:
    • const int input = 0;
    • const int output = 1;
    • const int append = 2;
  • int fileopenmode = input; //variable to keep track of mode

Enum

  • Better way to handle situation is to use enum
  • enum open_modes {input, output, append};
  • Defines an enumeration type called open_modes which can hold only one of the three listed values.
  • open_modes fileopenmode = input;
  • Fileopenmode variable is of type open_modes and can be assigned one of its enumerations ONLY.

Enum – 2

  • Enum superior to plain const:
    • validation is automatically performed
    • set of enumerations are defined at one place.
  • enum variables are assigned integral values with first enumeration being 0 by default and the others increasing by 1
  • See enumtest.cpp

Exercise

  • Write an enum type for weekday – Sunday, Monday …
  • Define two variables of that enum type
  • Assign some values for both variables in the program.
  • Print out the day of the week for both variables (string should be printed and not 0 or 1 …)
  • Compare the two variables and print whether they are equal or not.

——–

Note: The course book is C++ Primer, 4th Edition by Lippman, Lajoie and Moo. References above to source files, and use of code within those files, are of example code given in and/or along with the book. As this post is freely accessible on the Internet, not-for-profit, and for educational purposes, based on the permission related statements in the source code, I have considered that permission has been granted to use them here.