C classes
1 / 30

C++ Classes - PowerPoint PPT Presentation

  • Uploaded on

C++ Classes. Compiling C++ programs Input & output Class definition Member function definitions Utility functions Constructors Destructors Other member functions. C++. C++ is an enhanced version of C Object-oriented-programming capabilities Other improvements on C features

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about ' C++ Classes' - kuame-chapman

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
C classes
C++ Classes

  • Compiling C++ programs

  • Input & output

  • Class definition

  • Member function definitions

  • Utility functions

  • Constructors

  • Destructors

  • Other member functions


  • C++ is an enhanced version of C

    • Object-oriented-programming capabilities

    • Other improvements on C features

    • Is a “superset” of C

      • Can compile C programs with C++ compiler

  • Development

    • Bjarne Stroustrupat Bell Labs in early 1980’s

    • From C & Simula-67

    • Originally called “C with classes”

    • Later changed to “C++”

Compiling c programs
Compiling C++ Programs

  • For C++ files, end with “.cpp”

  • In UNIX, use “g++” compiler

    % g++ program.cpp

    % ./a.out


    % g++ program.cpp –o output

    % ./output

Makefile in c
Makefile in C++

  • Save following as “makefile”

    output: program.o

    <tab>g++ program.o -o output

    <blank line>

    program.o: program.cpp

    <tab>g++ -c program.cpp

    <blank line>

  • Type in “make” to run the makefile

    • % make

    • g++ -c program.cpp

    • g++ program.o -o output

    • % ./output

//A program that adds 2 integers (add.cpp)

#include <iostream>

using namespace std;

int main(){

int int1 = 0;

cout << "Enter an integer: ";

cin >> int1;

int int2 = 0;

cout << "Enter another integer: ";

cin >> int2;

int sum = int1 + int2;


return 0;


Header files namespace
Header Files & namespace

#include <iostream>

  • Preprocessor directive

  • Input/output stream header file

    • List of standard library header files (p. 533)

  • For programmer-defined header files

    • #include “myHeaderFile.h”

      using namespace std;

  • Standard C++ library namespace (used to prevent overlapping names)

Output input
Output & Input

cout << "Enter an integer: ";

  • Output values to the screen

  • Standard output stream (cout), or “see-out”

  • Stream insertion operator (<<), or “put to”

    cin >> int1;

  • Obtain a value from the keyboard

  • Standard input stream (cin), or “see-in”

  • Stream extraction operator (>>), or “get from”

C c differences
C & C++ Differences

  • C: procedural programming language

    • Programming is action-oriented

    • Function is basic unit of programming

C c differences1
C & C++ Differences

  • C++: object-oriented programming language

    • Programming is object-oriented

    • Class (a user-defined data type) is basic unit of programming

      • Attributes (data members)

      • Behaviors or operations (member functions)

    • Objects (variables) are created (instantiated) from the class

      • Regular variables (char, int, double, etc.) are instances of built-in data types

//Fraction class definition (ADT - abstract data type)

class Fraction{

public://accessible anywhere in program

//Constructor initializes each data member


num = 0;

den = 1;


//Set a new Fraction value & check data

void set(int n , int d ){

if(d == 0) d = 1;

if(d < 0) {d = -d; n = -n;}

num = n; den = d;


//Print a Fraction

void print() const{

cout << num << " / " << den;


private: //accessible only to member functions

intnum; //data member

int den; //data member

};//terminate class definition with a semicolon

Member access specifiers
Member Access Specifiers

  • public:

    • Any data member or data function declared after this is accessible anywhere in the program

  • private:

    • Any data member or data function declared after this is only accessible to member functions of the class

    • If no specifiers are declared, then the default is private

    • Can list specifiers in any order

  • protected:

    • Used for inheritance

Constant const
Constant (const)

  • Principle of least privilege

    • Users should be given no more privilege than necessary to perform a job

    • Good software engineering

  • Function definition

    void print() const{



    • Const member functions cannot modify the object’s data members (not allowed by compiler)

Driver program
Driver Program

// Driver program to test class Fraction

void main(){

//instantiate object f1 of class Fraction

Fraction f1;

f1.print(); // 0/1

//set the data

Fraction f2;

f2.set( 13, -27);

f2.print(); // -13/27

//attempt invalid data

Fraction f3;

f3.set( 99, 0);

f3.print(); // 99/1


//See complete program at fraction.cpp

Accessing class members
Accessing Class Members

/*Use accessor functions to change or access class member data (See access.cpp)*/

class Fraction {


int num, den;


Fraction(){num = 0; den = 1; }

void print() const{cout << num << "/" << den;}

void setNum(int n){num = n;}

void setDen(int d){if(d==0)d=1; den = d;}

int getNum(){return num;}

int getDen(){return den;}


Driver program1
Driver Program

// Driver program to test class Fraction

int main(){

//set & get the data

Fraction f2;



cout<<"f2's numerator is:"<<f2.getNum()<<endl;

cout<<" f2's denominator is:"<<f2.getDen()<<endl;

return 0;


//Fraction f2's numerator is: 13

//Fraction f2's denominator is: 27

Utility functions
Utility Functions

  • Not all member functions are public

  • Utility functions are private

    • Also called a “helper function”

    • Supports the operation of member functions

    • Not intended to be used by the clients of a class

      • Cannot use in the main() function

Utility functions1
Utility Functions

//See utility.cpp

class Fraction {



void set( int n = 0, int d = 1){

if(d==0) d = 1;

if(d < 0) {d = -d; n = -n;}

num = n; den = d;




int num, den;

void reduce(){...}


Utility functions2
Utility Functions

//Finds GCD using Euclid's algorithm (utility.cpp)


void reduce(){

int a = num;

int b = den;

while (b!=0){

int temp = a % b;

a = b;

b = temp;


num = num / a;

den = den / a;



void main(){

Fraction f3;

f3.set(6, 4);

f3.print(); // 3/2


Function overloading
Function Overloading

  • Functions have same name, different parameters

    #include <iostream>

    using namespace std;

    int square(int);

    double square(double);

    int main(){

    cout<<"square = "<<square(3)<<endl; //square = 9

    cout<<"square = "<<square(3.3)<<endl; //square = 10.89

    return 0;


    int square(int a){return a*a;}

    double square(double a){return a*a;}

    //See overload.cpp


  • A constructor is a class member function with the same name as its class

    • Used to initialize the class data members

    • Can have several overloaded constructors to initialize data members in different ways

    • Data to be initialized is put in parenthesis to the right of the object’s name

//Example of 3 overloaded constructors

class Fraction {

int num, den; //default is "private:"


Fraction(){ cout<<"constructor1"<<endl;

num = 0; den = 1; }

Fraction(int n) { cout<<"constructor2"<<endl;

num = n; den = 1; }

Fraction(int n, int d) {cout<<"constructor3"<<endl;

num = n; den = d; }


void main(){

Fraction f1, f2(2), f3(3,4);

Fraction f[5] = {Fraction(), Fraction(6), Fraction(7,8)};


  • What is the output?

    • See constructors.cpp

Reference variables
Reference Variables

  • Used as an alias for other variables

    • It is an automatically dereferenced pointer

      //see ref.cpp

      #include <iostream>

      using namespace std;

      int main(){

      int a = 7;

      int &b = a; /*put "&" in front of reference variable when declaring it*/


      cout<<"a="<<a<<" b="<<b<<endl;

      return 0;


      //a=8 b=8

Reference variables1
Reference Variables

  • Used in functions for call-by-reference

    #include <iostream>

    using namespace std;

    void square(int &);

    int main(){

    int c = 2;

    cout<<"c="<<c<<endl; //c=2


    cout<<"c="<<c<<endl; //c=4

    return 0;


    void square(int &d){

    d = d * d;


Copy constructor
Copy Constructor

  • Called in three cases

    • When initializing an object in a program with parenthesis

      Fraction a;

      Fraction b(a);

    • When initializing an object in a program with the equals sign (Note: this is not the default assignment operator)

      Fraction a;

      Fraction b = a;

    • When passing-by-value to a function

      void foo(Fraction f){...}

Copy constructor1
Copy Constructor

  • Can create your own copy constructor

    Fraction(const Fraction &f){




    • Otherwise the computer will create one for you

    • By default, performed by memberwise copy

      • Each data member of one object is copied to another object’s data members

      • Can cause problems with dynamically allocated data members (such as linked list)

    • Example code: copy.cpp


  • A destructor is a class member function with the same name as its class with a tilde (~) character in front of it

    • Called when an object is “destroyed”

      • When program execution leaves the scope in which the object of that class was instantiated

      • For global objects & static objects, when the program ends execution

    • Performs termination housekeeping so memory can be returned to the system

      • Useful for dynamically allocated data members (such as linked list)

class Fraction { //What’s the output?

int num, den;



Fraction(int n) {

num = n; den = 1;

cout<<"Constructor ("<<num<<"/"<<den<<")"<<endl;



~Fraction() {

cout<<"Destructor ("<<num<<"/"<<den<<")"<<endl;



Fraction f1(10);

int main(){

Fraction f2(20);


Fraction f3(30);

static Fraction f4(40);


Fraction f5(50);


} return 0;

} //See destructor.cpp

Other member functions
Other Member Functions

  • We can create any function that we wish for a class

    • For example, add(), subtract, multiply(), and divide() function for class Fraction

    • See math.cpp

      Fraction add(const Fraction &f){

      int num3 = num * f.den + den * f.num;

      int den3 = den * f.den;

      Fraction f3(num3, den3);


      return f3;


Passing parameters
Passing Parameters

  • When passing a parameter to a method

    • Call-by-reference more efficient than call-by-value

      • Call-by-value creates a “local copy” of the variable with the “copy constructor”

      • Call-by-reference simple maintains a “place-holder”, as the actual changes are make to the variable in the calling routine

    • Not a big deal with simple data types (int, etc.)

    • Can be a big deal with user-defined data types (that contain a lot of data)

For improved efficiency
For Improved Efficiency

  • When possible, make parameters call-by-reference

    • Can speed up execution for some data types

  • If the data members should not be changed, use “const” reference parameters

    • Can help to prevent programming bugs

    • Principle of least privilege

      • A function should not be able to change a parameter if it is not necessary