0% found this document useful (0 votes)
9 views

c_++

The document provides an overview of C and C++, highlighting their differences, with C being a procedural language and C++ an object-oriented language. It covers the basics of C++, including program structure, data types, control structures, functions, and memory management. Additionally, it discusses advanced topics such as inheritance, polymorphism, operator overloading, and the importance of constructors and destructors.

Uploaded by

Dipanshu Dhote
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

c_++

The document provides an overview of C and C++, highlighting their differences, with C being a procedural language and C++ an object-oriented language. It covers the basics of C++, including program structure, data types, control structures, functions, and memory management. Additionally, it discusses advanced topics such as inheritance, polymorphism, operator overloading, and the importance of constructors and destructors.

Uploaded by

Dipanshu Dhote
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

C and C++

• C is a Procedural Language :
“Decide which procedures you want; use the best algorithms you can find”

• C++ is an Object Oriented Language:


“Decide which modules you want; partition the program so that data is hidden within modules”

• C was chosen to be the base of C++ because:


1.C is versatile and terse
2.C is adequate for most systems programming tasks
3.C runs everywhere and on everything

Basics of C++
• Structure of a C++ program

• Variables and Data types

• Constants

• Operators

• Basic Input / output


Our First C++ Program
// my first program in C++
#include <iostream.h>

Using namespace std;

int main ()
{
cout << “Hello Cs169 / Fall 2009 Students“;
return 0;
}

Structure of a C++ Program


Comment
/* greeting.cpp greets its user.
*
* Input: The name of the user
* Output: A personalized greeting
*********************************************************/
#include <iostream> // cin, cout, <<, >>
#include <string> // string
using namespace std; Compiler
int main() Specifies standard
{ related names directives
cout << "Please enter your first name: ";
string firstName;
cin >> firstName;
cout << "\nWelcome to the world of C++, " << firstName << "!\n";
}

Main portion of 4
program.
Contains C++
statements.
Variables and Data Types

• Variable : a portion of memory to store a determined value.

• How to distinguish variables ? Identifiers

• Identifiers:
– Combination of letters, digits, and underscores
– Variable names should start with letter or digit

• Important : C++ is a “case sensitive” language

Fundamental DataTypes
Initialization of Variables
Two possibilities:

• type identifier = initial_value ;


• type identifier (initial_value) ;

Initialization of Variables
// initialization of variables
#include <iostream.h>

Using namespace std;

int main ()
{
int x=5;
int y(2);
int result;

x = x + 3;
result = x - y
cout << result;
return 0;
}
Strings
Example
// my first string
#include <iostream>
#include <string>
using namespace std;
int main () {

string mystring;
mystring = “Hello Cs169, Fall 2009";
cout << mystring << endl;
mystring = “Hello Cs169, I wish you a great semester";
cout << mystring << endl;
return 0;
}

Arithmetic Operators
Logical Operators ( !, &&, || )
Basic C++ I/O
• “iostream” C++ library
• Cout
cout << “Hello Cs169”; //Print Hello Cs169
cout << 120; // Print 120 on the screen
cout << x; // print the content of x in the screen
• Cin
int age;
cin >> age;
cout << age
cin >> a >> b; is equivalent to cin>>a; cin>>b;

Control structures

• if (cond) state1 else if (cond2) state2 else state3


• while (expression) statement
• do statement while (cond)
• for (init; cond; increment) statement;
Control structures
Example

Switch Statement
switch (x) { \
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default:
cout << "value of x unknown";
}
Functions
• We can use functions to achieve structured
programming
Int add(int a, int b){
a = a+b; return (a);
}

• ‘int’ is the return type, ‘a’ and ‘b’ are arguments


• When we call the function we must pass it
parameters matching the arguments

Passing Parameters
• Call By Value
– This is what we usually do, we pass a function
the value of a variable
• Call By Reference
– Instead of the value we will pass a pointer to
the variable. If we modify the passed variable
the change will be seen by the caller
– We use ‘&parm’ to show that we are passing
the variable at the memory location of parm
Agenda
Session 1

1. A Historical Perspective of C++ 5. Compound Data Types


Arrays
2. Major Differences between C and C++ Characters
Pointers
Dynamic Memory
3. Basics of C++
Structure of a program
6. C++ and Object Oriented Programming
Variables and Data types
Constants Classes
Operators Friendship and Inheritance
Basic Input / output Polymorphism

4. Control Structures
Structures
Functions

Arrays

• An Array is a set of elements of the same type located in contiguous


memory locations.

• An Array can be referenced using index


Arrays

• Intialization
– int numbers[5]={0,1,2,3,4,};
• Accessing
– num2 =numbers[1];
– numbers[0]=99;
• Passing arrays as parameters
– Declaration: int add(int numarray[])
– Call:
int array[]={1,2,3};
add(array);

Arrays
Example
Pointers

• We used pointers in call by reference


• A reference of a variable is the address that locates a
variable in Memory
• Pointer are Valuable in implementing data structures

Address Operator (&)


• The ‘&’ operator returns the ‘address of’ its
operand.
• ‘&’ can be translated ‘address of’
Pointers
Example

Sizeof()
• The Sizeof() function is used to determine
how many bytes of a data type during
compilation.
• Ex:
sizeof(float) equals 4
float array[10];
sizeof(array) equals 4*10 which is40
Dynamic Memory
• Dynamic Memory allows us to determine
and allocate memory to variables and data
structures at ‘run time’.
• C++ uses new and delete;
– pointer = new type;
• New returns a pointer to the allocated memory
– delete pointer;
• Frees up the memory that was allocated

Dynamic Memory
Example
Structs
• Similar to records in Ada.
struct person_t{
char fname[20];
char lname[20];
int age;
}person1, person2;
• Here we are declaring person1 and person2 as type
person_t.
• By convention we use the _t

Accessing the struct members


• We use the ‘.’ to access members of a struct
cout << person1.fname;
person1.fname=“John”;
Structs
Example

Pointers to Structs
• We can point to a struct like other structures.
Person_t* person1Ptr;
person1Ptr = &person1;
• We can no longer use the ‘.’ to access the
members in the struct we are pointing to.
– The ‘->’ is used
Cout << person1Ptr->fname;
– Element fname of structed pointed by person1Ptr
– Same as *(person1Ptr.fname);
C++ Classes
Example

Constructors
Example

Class Date { Date today(4);


int d,m,y Date july4(“july 4,1983)
Public: Date guy(“5 nov”)
//… Date now;
Date(int,int,int) //day,month, year
Date(int,int) //day, month, today’s
year
Date(int) //day, today’s month and
year
Date(); //default Date
Date(char*) // date in string
representation
}
Destructors
Example
class mystring {
private:
char *str;
int s; //size
public:
mystring(char *); // constructor
~mystring(); // destructor
};

mystring::mystring(char *c)
{
size = strlen(c);
str = new char[s+1];
strcpy(s,c);
}

mystring::~mystring()
{
delete []str;
}

Copy Constructor
Example
class myrectangle {
private:
float height;
float width;
int x;
int y;
public:
rectangle(float, float); // constructor
rectangle(const myrectangle&); // copy constructor
void draw(); // draw member function
void posn(int, int); // position member function
void move(int, int); // move member function
};
Importance of a copy
constructors
• In the absence of a copy constructor, the
C++ compiler builds a default copy
constructor for each class which is doing a
memberwise copy between objects.
• Default copy constructors work fine unless
the class contains pointer data members ...
why???

void string::copy(char *c)


{
strcpy(s, c);
}

void main()
{
string str1("George");
string str2 = str1; // default copy constructor

str1.print(); // what is printed ?


str2.print();

str2.copy("Mary");

str1.print(); // what is printed now ?


str2.print();
}
Defining a copy constructor
class mystring {
private:
char *s;
int size;
public:
mystring(char *); // constructor
~mystring(); // destructor
string(const mystring&); // copy constructor
void print();
void copy(char *);
};

Inheritance
• Objects are often defined in terms of
hierarchical classes with a base class and
one or more levels of classes that inherit
from the classes that are above it in the
hierarchy.
• For instance, graphics objects might be
defined as follows:
Inheritance
class A : base class access specifier B
{
member access specifier(s):
...
member data and member function(s);
...
}
Valid access specifiers include public, private,
and protected

Public Inheritance
class A : public B
{ // Class A now inherits the members of Class B
// with no change in the “access specifier” for
} // the inherited members

public base class (B) derived class (A)


public members public
protected members protected
private members inherited but not
accessible
Private Inheritance
class A : private B
{ // Class A now inherits the members of Class B
// with public and protected members
} // “promoted” to private

private base class (B) derived class (A)


public members private
protected members private
private members inherited but not
accessible

Inheritance (continued)
class Shape
{
public:
int GetColor ( ) ;
protected: // so derived classes can access it
int color;
};
class Two_D : public Shape
{
// put members specific to 2D shapes here
};
class Three_D : public Shape
{
// put members specific to 3D shapes here
};

Lect 28 P. 42 Winter Quarter


Function Overloading

• C++ supports writing more than one


function with the same name but different
argument lists. This could include:
– different data types
– different number of arguments
• The advantage is that the same apparent
function can be called to perform similar
but different tasks. The following will
show an example of this.

Operator Overloading
• Operator overloading means that the operators:

– Have multiple definitions that are distinguished by the


types of their parameters, and

– When the operator is used, the C++ compiler uses the


types of the operands to determine which definition
should be used.
Operator Overloading
Steps for defining an overloaded operator:

1. Name the operator being overloaded.

2. Specify the (new) types of parameters (operands) the


operator is to receive.

3. Specify the type of value returned by the operator.

4. Specify what action the operator is to perform.

Friends
• Basically, when you declare something as a friend,
you give it access to your private data members.
• This is useful for a lot of things – for very
interrelated classes, it more efficient (faster) than
using tons of get/set member function calls, and
they increase encapsulation by allowing more
freedom is design options.
Friends
• A class doesn't control the scope of friend
functions so friend function declarations are
usually written at the beginning of a .h file. Public
and private don't apply to them.

Friends
Example
Polymorphism
Compile-Time Binding vs.
Run-Time Binding
• A function’s name is associated with an entry
point, the starting address of the code that
implements the function
• Compile-time binding lets the compiler
determines what code is to be executed when a
function name is invoked
• Run-time binding is the binding of a function’s
name to an entry point when the program is
running
49

Polymorphism
Example

50

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy