0% found this document useful (0 votes)
19 views35 pages

CS3505 Lecture3

The document outlines the content of a lecture on Object-Oriented Programming in C++, focusing on key concepts such as encapsulation, abstraction, inheritance, and polymorphism. It covers the basics of C++ classes, constructors, and memory management, including dynamic allocation and operator overloading. Additionally, it contrasts C++ with Java in terms of memory management and object handling.

Uploaded by

liang19880404
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)
19 views35 pages

CS3505 Lecture3

The document outlines the content of a lecture on Object-Oriented Programming in C++, focusing on key concepts such as encapsulation, abstraction, inheritance, and polymorphism. It covers the basics of C++ classes, constructors, and memory management, including dynamic allocation and operator overloading. Additionally, it contrasts C++ with Java in terms of memory management and object handling.

Uploaded by

liang19880404
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/ 35

CS 3505: Software Practice II

Lecture 3:
Object-Oriented Programming in
C++
Assignment
• Some good questions and discussion on Piazza
(Some summaries and supporting assignment text)
– How do I make compile.txt and what is it?
• Cut-and-paste your compilation command into a text file
“Save the compilation command in a text file called compile.txt.”
– My populations are real close to the expected so good
enough?
• Compute changes in both populations before updating
“compute the change in population and then update R and F by
adding deltaRabbit and deltaFoxes respectively”
– The autograder says I have a wrong “\n” at the end
• The assignment asks you to add newlines elsewhere
“This function should not add a newline character to the bar chart
line”
C++ Classes
• Why object-oriented programming?
• Major principles
– Encapsulation
– Abstraction
– Inheritance
– Polymorphism
Goal of Object-Oriented Programming

• Make C++ look like a specialized language


for solving the problems you want to solve!
– Add types (objects) that support this
C-style Struct
• Collect related struct HealthInfo {
int id;
information into a
double weight;
named type bool rideMotorcycle;
structure bool smoke;
• Declare variables double height;
int age;
of that type
int exercise;
int drink;
HealthInfo dj; bool playVideoGamesAllNight)
};
Access is still an issue
HealthInfo dj;
dj.age = -10;
dj.drinks = ?

• Struct
– fails abstraction – internal representation has
to be known
– fails encapsulation – internals are exposed
C++ Class Basics
• Keyword class
• Data members (instance variables)
• Member functions - methods
• Constructor

• Make a point class


Class definition
class Point {

}; // don’t forget ;

• Point becomes a new type to use


Point mypoint;
Data members
• Make private data members
private:
double x,y;
• Keyword private: or public: or protected:
• Sets access mode until next access
keyword. Default start is private.
– Public: accessible to all code
– Protected: access to class code and derived
classes
– Private: only access from class code
• Friend code can also access
Constructors
• When you declare an object variable,
memory is reserved for the object’s data
members
• How are they initialized?
– Many ways
• Primitive data members have no default values
• Object data members have their default
constructor called
• All of this can be overridden in a constructor
Constructors
• System automatically makes a default
constructor
Point myPt; // calls default constructor

• You can overload the constructor to have


different parameters
• If you make your own, then need to also
make the default (if you want it).
Point() {} // a default constructor.
Point() = default; // new C++11 option
Custom Constructors
• Should assign values to each data
member
Point(int initx, int inity) {
x = initx;
y = inity;
}
– Data member x gets default constructed and then
initx is assigned to it.
Initializer List
• Rather than assign in constructor body
• Can use initializer list
• avoids default construction followed by assignment
– Handles case of no default constructor
– Avoids name clash
– Looks mysterious
Point(int x, int y) : x(x), y(y) { }
or (in C++11)
Point(int x, int y) : x{x}, y{y} { }
Brace-or-Equals initialization
• Can also provide default initialization for
data members directly
– Two different styles
private:
double x = 1.0, y {4};

These get used if not set in initializer list or


overridden in the constructor
Different Than Java
Java C++
Point c = new Point(2,3); Point center(2,3);
• Weirdly, the constructor
• Makes a new Point object notation hangs off the
using a constructor and variable name
assigns a reference to c • Never () for default
• The point goes away – just use
when nothing is Point center;
referencing it. • Deconstructed when
• Without the new, is just a leave scope
reference. • What do you think of
Point center = Point(2,3);
Accessing Members of a Class
• For an object P1 we can access public
members by
– “dot” notation: P1.x; P1.display();
• For a pointer to an object, P1ptr, we use
– “arrow” notation: P1ptr->x; P1ptr->display
• These are legal, but mostly weird
(&P1)->x; (*P1ptr).x
• Inside class code, the keyword “this” is a
pointer to the object that called a method
this->x *this is the actual object
Class Methods
• Typically fall into a few categories
– Constructors
– Setters/getters
– Operators
– Normal methods
Setters/Getters
• Also a religious war topic
– Typical setter/getter
// Get the value of the private x data member
int get_x() {
return x;
}
// Set the value of the private x data member
void set_x(double newx) {
x = newx;
}
– Why is this contentious?
Overloading Operators
• We want our data types to act like built-in
types
newpt = pt * 2.0;
• Overload operators
– List of operators
– https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
Model for Overloading
• The compiler transforms the infix notation
to a method or function call

newpt = pt * 2.0;
becomes
newpt = pt.operator*(2.0);
Once you know that, defining them is easy
An Overloaded *
• One way
Point operator*(double scaleFactor) {
Point res;
res.x = x * scaleFactor;
res.y = y * scaleFactor;
return res;
};
• Another
Point res(x * scaleFactor, y * scaleFactor);
return res;
Overload <<
• Want
cout << myPoint << endl;

– What does this get transformed into?


• << is evaluated left-to-right
• So cout << myPoint needs to
evaluate to a stream so the << endl
works.
Need to be outside friend
function
• In class, prototype the friend function
friend ostream& operator<<(ostream& output,
Point pt);

• Outside class, make function


ostream& operator<<(ostream& output, Point pt)
{
output << "(" << pt.x << "," << pt.y << ")";
return output;
}

• & makes a reference to the original stream


• Doesn’t need friend if it uses getters to access
data members
Break
New and Delete
• Can dynamically
allocate memory int* p = new int(4);
– New allocates space
for object and calls
delete p;
constructor
– Delete frees up the
memory
• Allocation on the heap
– Fairly expensive
operation
• Look at var table
New and Delete
• Can dynamically
allocate memory int* p = new int(4);
– New allocates space
for object and calls
delete p;
constructor
– Delete frees up the Symbol table
memory
int* p 1000
• Allocation on the heap Stack
– Fairly expensive
operation 1000: 4000
• Look at var table Heap
4000: 4
Arrays
• Can dynamically allocate an array
int *x = new int[10];
x[0] = 5;
• Note the equivalence of C-style arrays and
pointers
• Special delete
delete [] x;
• Pointer math – knows underlying size
x++;
*(x+1)
Problems
• Memory leak for (unsigned int i = 0;
– For every new called, i < 1000000000;
need a delete i++ ) {
• End of the program int* p = new int(4);
cleans up your }
messes
– Do not rely on that
C++ Function Return Styles
int getVal()
• the value of the expression in the return is copied
and returned to the calling code.
int& getVal()
• A reference to the return object is returned. This
better not be to a local leaving scope.
int* getVal()
• a pointer to an int is returned. The return better
return an address to something, and that
something should persist after the function is
done.
Java Detox
A Reminder of Java
• Declare a variable
Point center;
• These are really reference types
– no allocation of memory for a Point
• Assign it to an object allocated with new
center = new Point();
– the object is smart and knows how many
references use that object
– the object removes itself when no more
references
Declare variables
Java C++
• Point center; • Point center;
– make a ref waiting to get – allocate memory for a
an object Point using the default
– If assigned, the ref count constructor
goes down when center – center is fully usable
leaves scope after this statement
– object is destructed
when center leaves
scope
– Instance variables
• Primitives go away
• Destructor called on
objects
New
Java C++
• Point c = new Point(2,3) • Point* center = new Point();

• new creates a Point • new allocates memory for a


object that deallocates Point and calls a
itself when no more constructor
– it returns an address to the
references memory
– that address must be stored
in a pointer
• Must use a delete on the
pointer to free the memory
New
Java C++
• Point c = new Point(2,3) • Point* center = new Point();

• new object reference is • output of new is only


assigned to implicit assigned to pointers.
reference type. • Not
Point center = new Point();
• Not even to a reference
Point& center = new Point();
this
Java C++
• this holds a reference to • this is pointer to the object
the object that called a that called a method.
method.

this.update(); this->update();

You might also like