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

CSCI 104 Classes: Mark Redekopp David Kempe

Classes provide a way to encapsulate related data and operations into a single unit. They allow data and code to be grouped together to create abstractions and reduce coupling between components. The main parts of a C++ class include member variables to store data, constructors to initialize instances, member functions to interact with the data, and destructors to clean up instances. Member functions implicitly receive the object being operated on via the 'this' pointer. Constructors are called when a class is instantiated to initialize member variables, as C++ does not do this automatically.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
144 views

CSCI 104 Classes: Mark Redekopp David Kempe

Classes provide a way to encapsulate related data and operations into a single unit. They allow data and code to be grouped together to create abstractions and reduce coupling between components. The main parts of a C++ class include member variables to store data, constructors to initialize instances, member functions to interact with the data, and destructors to clean up instances. Member functions implicitly receive the object being operated on via the 'this' pointer. Constructors are called when a class is instantiated to initialize member variables, as C++ does not do this automatically.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

1

CSCI 104
Classes
Mark Redekopp
David Kempe
2

CLASSES
3

C Structs
• Needed a way to group values that are
related, but have different data types
• NOTE: struct has changed in C++! struct Person{
char name[20];
int age;
–C };
• Only data members int main()
{
• Some declaration nuances // Anyone can modify
– C++ // b/c members are public
Person p1;
• Like a class (data + member functions) p1.age = -34;
// probably not correct
• Default access is public return 0;
}
4

Classes & OO Ideas


• In object-oriented programming languages (C++) classes are used as the
primary way to organize code
• Encapsulation
– Place data and operations on data into one code unit struct Machine{
Piece* pieces;
– Keep state hidden/separate from other Engine* engine;
};
programmers via private members
int main()
• Abstraction {
Machine m;
– Depend only on an interface!
init_subsystemA(&m);
• Ex. a microwave…Do you know how it works?
But can you use it? change_subsystemB(&m);
– Hide implementation details to create low replace_subsystemC(&m);
degree of coupling between different
m.start();
components // Seg. Fault!! Why?
• Polymorphism & Inheritance }

– More on this later…


Protect yourself from users & protect your
users from themselves
5

Coupling
• Coupling refers to how much components depend on each
other's implementation details (i.e. how much work it is to
remove one component and drop in a new implementation of
it)
– Placing a new battery in your car vs. a new engine
– Adding a USB device vs. a new video card to your laptop
• OO Design seeks to reduce coupling as much as possible by
– Creating well-defined interfaces to change (write) or access (read) the
state of an object
– Enforcing those interfaces are adhered to
• Private vs. public
– Allow alternate implementations that may be more appropriate for
different cases
6

C++ Classes
• A composition mechanism
– Create really large and powerful software systems from tiny
components
– Split things up into manageable pieces
• Somewhat of a bottom up approach (define little pieces that can be used
to compose larger pieces)
– Delegation of responsibility
• An abstraction and encapsulation mechanism
– Make functionality publicly available, but hide data & implementation
details
• A mechanism for polymorphism
– More on this later
7

C++ Classes: Overview


• What are the main parts of a class?
– Member variables
• What data must be stored?
– Constructor(s)
• How do you build an instance?
– Member functions
• How does the user need to interact with the stored
data?
– Destructor
• How do you clean up an after an instance?
8

C++ Classes: Overview


• Member data can be public or private (for now)
– Defaults is private (only class functions can access)
– Must explicitly declare something public
• Most common C++ operators will not work by default
(e.g. ==, +, <<, >>, etc.)
– You can't cout an object ( cout << myobject; won't work )
– The only one you get for free is '=' and even that may not work the
way you want (more on this soon)
• Classes may be used just like any other data type (e.g. int)
– Get pointers/references to them
– Pass them to functions (by copy, reference or pointer)
– Dynamically allocate them
– Return them from functions
9


this Pointer
How do member functions know which 0x7e0

object’s data to be operating on? cards[52] 37 21 4 9 16 43 20 39


• d1 is implicitly passed via a special pointer top_index
0
d2
call the ‘this’ pointer
#include<iostream> 0x2a0
#include “deck.h” cards[52]

poker.cpp
41 27 8 39 25 4 11 17
int main(int argc, char *argv[]) { d1
passed to shuffle()

top_index
Deck d1, d2; 1
d1 is implicitly

d1.shuffle();

this int main() { Deck d1;


d1.shuffle();
#include<iostream>
0x2a0 }
#include “deck.h”
void Deck::shuffle(Deck *this)
void Deck::shuffle() {
d1.shuffle();
{ ... this->cut(); // calls cut()
// for this object
} cut(); // calls cut()
// for this object for(i=0; i < 52; i++){
for(i=0; i < 52; i++){ int r = rand() % (52-i);

deck.cpp
int r = rand() % (52-i); int temp = this->cards[r];
deck.cpp

int temp = cards[r]; this->cards[r] = this->cards[i];


cards[r] = cards[i]; this->cards[i] = temp;
cards[i] = temp; }
} }
} Actual code you write Compiler-generated code
10

Exercises
• cpp/cs104/classes/this_scope
11

Another Use of 'this'


class Student {

• This can be used public:


Student(string name, int id, double gpa);

to resolve ~Student(); // Destructor


private:
string name;
scoping issues int id;
double gpa;

with similar };

named variables Student::Student(string name, int id, double gpa)


{ // which is the member and which is the arg?
name = name; id = id; gpa = gpa;
}

Student::Student(string name, int id, double gpa)


{ // Now it's clear
this->name = name;
this->id = id;
this->gpa = gpa;
}
12

C++ Classes: Constructors


• Called when a class is instantiated
– C++ won't automatically initialize member variables
– No return value class Item
• Default Constructor { int val;
public:
– Can have one or none in a class Item(); // default const.
– Basic no-argument constructor Item(int v); // overloaded
};
– Has the name ClassName()
– If class has no constructors, C++ will make a default
• But it is just an empty constructor (e.g. Item::Item() { } )
• Overloaded Constructors
– Can have zero or more
– These constructors take in arguments
– Appropriate version is called based on how many and what type of arguments
are passed when a particular object is created
– If you define a constructor with arguments you should also define a default
constructor
13

Identify that Constructor


#include <string>

• Prototype what #include <vector>


using namespace std;

constructors are being int main()


{
called here string s1;
string s2("abc");

vector<int> dat(30);

return 0;
}
14

Identify that Constructor


#include <string>
• Prototype what constructors #include <vector>
using namespace std;
are being called here int main()
{
• s1 string s1;
string s2("abc");
– string::string()
vector<int> dat(30);
// default constructor
return 0;
• s2 }

– string::string(const char* )
• dat
– vector<int>::vector<int>( int );
15

Exercises
• cpp/cs104/classes/constructor_init
16

Consider this Struct/Class


• Examine this struct/class definition…
#include <string>
#include <vector>
using namespace std;

struct Student
{
string name;
int id;
vector<double> scores;
// say I want 10 test scores per student string name

int id
};
scores
int main()
{
Student s1;
}
17

Composite Objects
• Fun Fact: Memory for an object comes alive before the code
for the constructor starts at the first curly brace '{'
#include <string>
#include <vector>
using namespace std;

struct Student
{
string name;
int id;
vector<double> scores; string name
// say I want 10 test scores per student
int id
Student() /* mem allocated here */
{ scores
// Can I do this to init. members?
name("Tommy Trojan");
id = 12313;
scores(10);
}
};

int main()
{
Student s1;
}
18

Composite Objects
• You cannot call constructors on data members once the
constructor has started (i.e. passed the open curly '{' )
– So what can we do??? Use initialization lists!
#include <string>
#include <vector>
using namespace std;

struct Student
{
string name; string name
int id;
vector<double> scores; int id
// say I want 10 test scores per student
scores
Student() /* mem allocated here */
{
This would be
// Can I do this to init. members?
name("Tommy Trojan"); "constructing"
id = 12313; name twice. It's
scores(10); too late to do it in
} the {…}
};

int main()
{
Student s1;
}
19

Constructor Initialization Lists


Student::Student() Student::Student() :
{ name(), id(), scores()
name = "Tommy Trojan"; // calls to default constructors
id = 12313 {
scores.resize(10); name = "Tommy Trojan";
} id = 12313
scores.resize(10);
}

If you write this…


The compiler will still generate this.

• Though you do not see it, realize that the default


constructors are implicitly called for each data
member before entering the {…}
• You can then assign values but this is a 2-step
process
20

Constructor Initialization Lists


Student:: Student() /* mem allocated here */ Student::Student() :
{ name("Tommy"), id(12313), scores(10)
name("Tommy Trojan"); { }
id = 12313;
scores(10);
}

You can't call member You would have to call the member
constructors in the {…} constructors in the initialization list context

• Rather than writing many assignment statements


we can use a special initialization list technique
for C++ constructors
– Constructor(param_list) : member1(param/val), …, memberN(param/val)
{…}

• We are really calling the respective constructors


for each data member
21

Constructor Initialization Lists


Student::Student() Student::Student() :
{ name(), id(), scores()
name = "Tommy Trojan"; // calls to default constructors
id = 12313 {
scores.resize(10); name = "Tommy Trojan";
} id = 12313
scores.resize(10);
}
You can still assign data But any member not in the initialization list will
members in the {…} have its default constructor invoked before the
{…}

• You can still assign values in the constructor but


realize that the default constructors will have
been called already
• So generally if you know what value you want to
assign a data member it's good practice to do it
in the initialization list
22

Exercises
• cpp/cs104/classes/constructor_init2
23

Member Functions
class Item
• Have access to all member { int val;
public:
variables of class void foo();
void bar() const;
};
• Use “const” keyword if it void Item::foo() // not Foo()
{ val = 5; }
won't change member data
void Item::bar() const
• Normal member access uses { }

int main()
dot (.) operator {
Item x;
• Pointer member access uses x.foo();
Item *y = &x;
(*y).bar();
arrow (->) operator y->bar(); // equivalent
return 0;
}
24

Exercises
• cpp/cs104/classes/const_members
• cpp/cs104/classes/const_members2
• cpp/cs104/classes/const_return
25

C++ Classes: Destructors


• Called when a class goes out of scope or is freed from the heap (by
“delete”)
• Why use it?
– Not necessary in simple cases
– Clean up resources that won't go away automatically (e.g. stuff you used
“new” to create in your class member functions or constructors
• Destructor
– Has the name ~ClassName()
– Can have one or none
– No return value
– Destructor (without you writing any code) will automatically call destructor of
any data member objects…but NOT what data members point to!
• You only need to define a destructor if you need to do more than that (i.e. if you
need to release resources, close files, deallocate what pointers are point to, etc.)
26

C++ Classes: Other Notes


#ifndef ITEM_H
• Classes are generally split across two #define ITEM_H
files class Item
{ int val;
– ClassName.h – Contains interface public:
description void foo();
void bar() const;
– ClassName.cpp – Contains };
implementation details #endif
• Make sure you remember to prevent item.h
multiple inclusion errors with your
header file by using #ifndef, #define, #include "item.h"
and #endif void Item::foo()
{ val = 5; }
#ifndef CLASSNAME_H
#define CLASSNAME_H void Item::bar() const
{ }
class ClassName { … };
item.cpp
#endif
27

CONDITIONAL COMPILATION
28

Multiple Inclusion
class string{
• Often separate files may ... };

#include's of the same header string.h


#include "string.h"
file class Widget{
public:
• This may cause compiling string s;
};
errors when a duplicate
widget.h
declaration is encountered #include "string.h"
– See example #include "widget.h"
int main()
• Would like a way to include only { }

once and if another attempt to main.cpp


include is encountered, ignore it class string { // inc. from string.h
};
class string{ // inc. from widget.h
};
class Widget{
... }
int main()
{ }

main.cpp after preprocessing


29

Conditional Compiler Directives


#ifndef STRING_H
• Compiler directives start with #define STRING_H
class string{
'#' ... };
#endif
– #define XXX String.h
• Sets a flag named XXX in the #include "string.h"
compiler class Widget{
public:
– #ifdef, #ifndef XXX … #endif string s;
};
• Continue compiling code below
until #endif, if XXX is (is not) Character.h
defined
#include "string.h"
• Encapsulate header #include "string.h"

main.cpp
declarations inside a
– #ifndef XX class string{ // inc. from string.h
};
#define XX
class Widget{ // inc. from widget.h
… ...
#endif main.cpp after preprocessing
30

Conditional Compilation
• Often used to compile int main()
{
additional DEBUG code int x, sum=0, data[10];
– Place code that is only needed for ...
for(int i=0; i < 10; i++){
debugging and that you would not want sum += data[i];
to execute in a release version #ifdef DEBUG
cout << "Current sum is ";
• Place code in a #ifdef cout << sum << endl;
#endif
XX...#endif bracket }
cout << "Total sum is ";
• Compiler will only compile if a cout << sum << endl;

#define XX is found stuff.cpp

• Can specify #define in: $ g++ -o stuff –DDEBUG stuff.cpp

– source code
– At compiler command line with
(-Dxx) flag
• g++ -o stuff –DDEGUG stuff.cpp
31

PRE SUMMER 2016


32

Example Code
• Login to your VM, start a terminal
• Best approach – Clone Lecture Code Repo
– $ git clone [email protected]:usc-csci104-fall2015/r_lecture_code.git lecture_code
– $ cd lecture_code/coninit
– $ make coninit
• Alternate Approach – Download just this example
– Create an 'lecture_code' directory
– $ wget http://ee.usc.edu/~redekopp/ee355/code/coninit.cpp
– $ make coninit

You might also like