1 of 55

C++ Classes – Midterm Recapitulation

C. Papachristos

Robotic Workers Lab

University of Nevada, Reno

CS-202

2 of 55

Course , Projects , Labs:

Your 6th Project Deadline is this Wednesday 3/11.

Your Midterm will be held this Thursday 3/12.

  • A Midterm Sample has been announced since last week.
  • Lectures, PASS sessions (with a Sunday extra), dedicated to recapitulation.
  • Final recap, questions & Midterm Sample overview today!

Monday

Tuesday

Wednesday

Thursday

Friday

Sunday

 

 

 

Lab (8 Sections)

 

 

RECAP CLASS

PASS

Session

CLASS

 

PASS

Session

Project DEADLINE

MIDTERM

 PASS

Session

 PASS

Session

Course Week

CS-202 C. Papachristos

3 of 55

Today’s Topics

CS-202 C. Papachristos

C++ Classes Cheatsheet

  • Declaration
  • Members, Methods, Interface
  • Implementation – Resolution Operator ( :: )
  • Instantiation – Objects
  • Object Usage – Dot Operator ( . )
  • Object Pointer Usage – Arrow Operator ( -> )
  • Classes as Function Parameters, Pass-by-Value, by-(const)-Reference, by-Address
  • Protection Mechanisms – const Method signature
  • Classes – Code File Structure
  • Constructor(s), Initialization List(s), Destructor
  • static Members – Variables / Functions
  • Class friend(s)
  • Keyword this
  • Operator Overloading
  • Class/Object Relationships – Composition, Aggregation,
  • Inheritance – Rules, Method Overriding
  • Polymorphism – Base Class Pointers ( Abstract Data Structure(s) support )
  • virtual Methods – Static vs Dynamic Binding
  • Pure virtual Methods – Abstract Classes

4 of 55

Functions - Examples

CS-202 C. Papachristos

Implementing Helper Functions

int strcmp(const char * s1, const char * s2)

{

while (*s1 == *s2++){

if (!*s1++){

return 0;

}

}

return *s1 - *--s2;

}

void strcpy(char * dst, const char * src)

{

while (*dst++ = *src++);

}

int strlen(const char * str)

{

const char * s = str;

for ( ; *s; ++s);

return s - str;

}

const int STR_MAX = 256;

  • For C-string types�(char arrays – i.e. char *)

5 of 55

Functions - Examples

CS-202 C. Papachristos

Implementing Helper Functions

char * strcat(char * dst, const char * src)

{

strcpy( dst + strlen(dst), src);

return dst;

}

int strlen(const char * str)

{

const char * s = str;

for ( ; *s; ++s);

return s - str;

}

const int STR_MAX = 256;

  • For C-string types�(char arrays – i.e. char *)

int strcpy(char * dst, const char * src)

{

while (*dst++ = *src++);

}

6 of 55

Functions - Examples

CS-202 C. Papachristos

Implementing Helper Functions

void intcpy(int * dst, const int * src, int size){

while (--size>=0){

*dst++ = *src++;

}

}

void intcmp(const int * arr1, const int * arr2, int size){

while (--size>=0){

int res = *arr1++ - *arr2++;

if (res){ return res; }

}

return 0;

}

void intprint(std::ostream & os, const int * arr, int size){

while (--size>=0){

os << *arr++;

}

}

  • Similarly for any other type (float *, double *, etc.)

7 of 55

Declare a Base Class, Implement some Methods

const size_t STR_MAX = 255;

const char * BOOK_DEFAULT_TITLE = "notitle";

const char * BOOK_DEFAULT_RENTER = "norenter";

class Book {

friend std::ostream & operator<<(std::ostream & os, const Book & b);

public:

Book();

Book(const char * title,

const char * renter = BOOK_DEFAULT_RENTER); //use default parameters in list

Book(const Book & other);

~Book();

Book & operator=(const Book & rhs);

size_t getID() const;

void setTitle(const char * title);

const char * getTitle() const;

Classes - Examples

CS-202 C. Papachristos

  • Global constants can be of builtin type,�array-type,�C-string type, etc.

8 of 55

Declare a Base Class, Implement some Methods

const size_t STR_MAX = 255;

const char * BOOK_DEFAULT_TITLE = "notitle";

const char * BOOK_DEFAULT_RENTER = "norenter";

class Book {

friend std::ostream & operator<<(std::ostream & os, const Book & b);

public:

Book();

Book(const char * title,

const char * renter = BOOK_DEFAULT_RENTER); //use default parameters in list

Book(const Book & other);

~Book();

Book & operator=(const Book & rhs);

size_t getID() const;

void setTitle(const char * title);

const char * getTitle() const;

Classes - Examples

CS-202 C. Papachristos

  • Strict methodology about overloading certain operators, managing access (e.g.,�const-qualification of methods that do not allow calling object mutation), etc.

9 of 55

Declare a Base Class, Implement some Methods

const size_t STR_MAX = 255;

const char * BOOK_DEFAULT_TITLE = "notitle";

const char * BOOK_DEFAULT_RENTER = "norenter";

class Book {

friend std::ostream & operator<<(std::ostream & os, const Book & b);

public:

Book();

Book(const char * title,

const char * renter = BOOK_DEFAULT_RENTER); //use default parameters in list

Book(const Book & other);

~Book();

Book & operator=(const Book & rhs);

size_t getID() const;

void setTitle(const char * title);

const char * getTitle() const;

Classes - Examples

CS-202 C. Papachristos

  • Getters/Setters/Helpers all should follow rules about�allowing / restricting mutation if so specified ! ! !

10 of 55

Classes - Examples

CS-202 C. Papachristos

  • Default parameters�(if specified) appear only in function declarations !

Declare a Base Class, Implement some Methods

const size_t STR_MAX = 255;

const char * BOOK_DEFAULT_TITLE = "notitle";

const char * BOOK_DEFAULT_RENTER = "norenter";

class Book {

friend std::ostream & operator<<(std::ostream & os, const Book & b);

public:

Book();

Book(const char * title,

const char * renter = BOOK_DEFAULT_RENTER); //use default parameters in list

Book(const Book & other);

~Book();

Book & operator=(const Book & rhs);

size_t getID() const;

void setTitle(const char * title);

const char * getTitle() const;

11 of 55

Declare a Base Class, Implement some Methods

bool available() const ;

bool valid() const ;

bool operator+(const char * renter);

void free();

virtual void serialize(std::ostream & os) const ;

static size_t getIdgen();

static size_t getTrash();

private:

const size_t m_id;

char m_title[STR_MAX];

char m_renter[STR_MAX];

static size_t s_idgen;

static size_t s_trash;

};

Classes - Examples

CS-202 C. Papachristos

  • const data members ! ! !

  • Strict methodology about�const-qualification of methods that do not allow calling object mutation), etc.

  • static member functions & data

12 of 55

Declare a Base Class, Implement some Methods

bool available() const ;

bool valid() const ;

bool operator+(const char * renter);

void free();

virtual void serialize(std::ostream & os) const ;

static size_t getIdgen();

static size_t getTrash();

private:

const size_t m_id;

char m_title[STR_MAX];

char m_renter[STR_MAX];

static size_t s_idgen;

static size_t s_trash;

};

Classes - Examples

CS-202 C. Papachristos

  • const data members ! ! !

  • Strict methodology about�const-qualification of methods that do not allow calling object mutation), etc.

  • static member functions & data

  • Dynamic�Binding?

13 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Base Class, Implement some Methods

size_t Book::s_idgen = 0; //do not forget static member definition

size_t Book::s_trash = 0; //do not forget static member definition

Book::Book()

: m_id( s_idgen++ ) //member is const, have to use initializer list to set it

//in all constructors

{

setTitle(BOOK_DEFAULT_TITLE); //code reuse - set the title to default

free(); //code reuse - mark as free

}

  • Initializer Lists are only used with Constructors�and appear only in implementations !

  • Re-use functionalities that should�be there according to specifications !

14 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Base Class, Implement some Methods

Book::Book(const char * title, const char * renter)

: m_id( s_idgen++ ) //member is const, have to use initializer list to set it

//in all constructors

{

setTitle(title); //code reuse - set the title using passed parameter

free(); //code reuse - mark as free first but then check whether the user put in

//an actual renter name or left everything to the default parameter list

if ( strcmp(renter, BOOK_DEFAULT_RENTER) ){

(*this) + renter; // note - cannot do: this->+(renter)

// the correct alternative is: this->operator+(renter)

}

}

  • Do NOT confuse with:� if (renter == BOOK_DEFAULT_RENTER) …!

15 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Base Class, Implement some Methods

Book::Book(const Book & other)

: m_id( s_idgen++ ) //member is const, have to use initializer list to set it

//in all constructors

{

setTitle(other.m_title); //code reuse - set the title using other object data

free(); //custom copy constructor will make book copy but mark new object as free

}

Book::~Book()

{

++s_trash; //increment count of destroyed objects

}

16 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Base Class, Implement some Methods

Book & Book::operator=(const Book & rhs){

//always check for self-assignment first

if (this != &rhs){

//cannot do anything to const int m_id

setTitle(rhs.m_title); //code reuse - set the title using rhs object data

//has to be free before invoking operator+ to guarantee success of renting it

free();

(*this) + rhs.m_renter; //code reuse – operator+ to add other object’s renter

}

return *this; //return calling object by-reference (method returns object &)

}

  • Rules & Methodology expected to be followed to–the–Letter ! ! !

17 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Base Class, Implement some Methods

size_t Book::getID() const {

return m_id;

}

void Book::setTitle(const char * title){

strcpy(m_title, title);

}

const char * Book::getTitle() const {

return m_title;

}

  • const–correctness applies at all times ! ! !

18 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Base Class, Implement some Methods

bool Book::operator+(const char * renter){ //const correctness even for parameters!� //basic sanity check: is the book available? is it valid?� // are we giving a valid name for the renter?

if (available() && valid() &&

strcmp(renter, BOOK_DEFAULT_RENTER) //remember: strcmp match returns 0

)

{

strcpy(m_renter, renter);

return true; //success

}

else{

return false; //failure

}

}

  • Do NOT confuse with:� m_renter = renter …!

19 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Base Class, Implement some Methods

void Book::free(){

strcpy(m_renter, BOOK_DEFAULT_RENTER);

}

bool Book::valid() const { //use specified values that signify object state

if (!strcmp(m_title, BOOK_DEFAULT_TITLE)){

return false;

}

return true;

}

bool Book::available() const { //use specified values that signify object state

if (!strcmp(m_renter, BOOK_DEFAULT_RENTER)){

return false;

}

return true;

}

  • Do NOT confuse with:� if (m_title == BOOK_DEFAULT_TITLE) … (etc) !

20 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Base Class, Implement some Methods

size_t Book::getIdgen(){ //static member function but no static keyword in definition

return s_idgen;

}

size_t Book::getTrash(){ //static member function but no static keyword in definition

return s_trash;

}

21 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Base Class, Implement some Methods

void Book::serialize(std::ostream & os) const {

os << m_title <<" (" << m_id << ") ";

if (available()){

os << " Free for rent";

}

else{

os << " Rented to: " << m_renter;

}

}

std::ostream & operator<<(std::ostream & os, const Book & b){ //not a member function!

b.serialize(os);

return os;

}

  • Rules & Methodology expected to be followed to–the–Letter ! ! !

22 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Derived Class, Override some Methods

class ChildrenBook : public Book {

protected:

char m_title[STR_MAX];

};

class ChildrenBook : public Book {

public:

ChildrenBook();

ChildrenBook(bool picturebook, const char * title,

const char * renter = BOOK_DEFAULT_RENTER); //default params

ChildrenBook(const ChildrenBook & other);

ChildrenBook & operator=(const ChildrenBook & rhs);

virtual void serialize(std::ostream & os) const;

private:

bool m_picturebook;

};

  • If necessary, modify (rewrite part of the Base class declaration)

  • Some Base methods will require overriding !

23 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Derived Class, Override some Methods

class ChildrenBook : public Book {

protected:

char m_title[STR_MAX];

};

class ChildrenBook : public Book {

public:

ChildrenBook();

ChildrenBook(bool picturebook, const char * title,

const char * renter = BOOK_DEFAULT_RENTER); //default params

ChildrenBook(const ChildrenBook & other);

ChildrenBook & operator=(const ChildrenBook & rhs);

virtual void serialize(std::ostream & os) const;

private:

bool m_picturebook;

};

  • If necessary, modify (rewrite part of the Base class declaration)

  • Some Base methods will require overriding !

  • Dynamic�Binding?

24 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Derived Class, Override some Methods

ChildrenBook::ChildrenBook()

: Book( ) //Base default ctor invocation in member initializer list

, m_picturebook(true)

{

}

ChildrenBook::ChildrenBook(bool picturebook, const char * title, const char * renter)

: Book(title, renter) //Base parametrized ctor invocation in member initializer list

, m_picturebook(picturebook)

{

}

ChildrenBook::ChildrenBook(const ChildrenBook & other)

: Book(other) //Base copy ctor invocation in member initializer list

, m_picturebook(other.m_picturebook)

{

}

  • Member Initializer Lists is the only way to specify the Base construction method !!!

25 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Derived Class, Override some Methods

ChildrenBook & ChildrenBook::operator=(const ChildrenBook & rhs){

//always check for self-assignment first

if (this != &rhs){

m_picturebook = rhs.m_picturebook; //assignment on Derived parts

Book::operator=(rhs); //code reuse for Base parts

}

return *this; //return calling object by-reference (method returns object &)

}

  • Rules & Methodology expected to be followed to–the–Letter ! ! !

26 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Base Class, Implement some Methods

void ChildrenBook::serialize(std::ostream & os) const {

os << m_picturebook << " "; //output Derived parts

Book::serialize(os); //output Base parts (some are private, thus inaccessible!)

//leverage code reuse of Base class public interface!

}

std::ostream & operator<<(std::ostream & os, const ChildrenBook & cb){

cb.serialize(os);

return os;

}

27 of 55

Classes - Examples

CS-202 C. Papachristos

Declare a Base Class, Implement some Methods

void ChildrenBook::serialize(std::ostream & os) const {

os << m_picturebook << " "; //output Derived parts

Book::serialize(os); //output Base parts (some are private, thus inaccessible!)

//leverage code reuse of Base class public interface!

}

std::ostream & operator<<(std::ostream & os, const ChildrenBook & cb){

cb.serialize(os);

return os;

}

  • We won’t need such a non-member function for Derived objects,�as long as we enable a C++ feature !!!

28 of 55

Classes - Examples

CS-202 C. Papachristos

Work with an Aggregate Class

const size_t LIBRARY_SIZE = 1000;

class Library {

friend std::ostream& operator<<(std::ostream& os,

const Library& l);

public:

Library();

Children * findOpenSpot();

Children * operator[](const char * title);

const Children & operator[](size_t index) const;

bool rentBook(const char * title, const char * name);

bool operator+(const ChildrenBook & childrenbook);

private:

ChildrenBook m_inventory[LIBRARY_SIZE];

};

  • No user-declared constructor,�BUT how are the class members constructed ?

29 of 55

Classes - Examples

CS-202 C. Papachristos

Work with an Aggregate Class

ChildrenBook * Library::findOpenSpot(){

ChildrenBook * m_inventory_pt = m_inventory;

for (size_t i=0; i<LIBRARY_SIZE; ++i){

if ( !m_inventory_pt->valid() ){ //code reuse: if the object at that index

//is not valid, it can be considered

//as "open-to-assign"

return m_inventory_pt; //found one

}

++m_inventory_pt;

}

return NULL; //found none

}

  • Index by-Member-Value (here internal state with interface valid) and return Pointer-to-Data !

30 of 55

Classes - Examples

CS-202 C. Papachristos

Work with an Aggregate Class

ChildrenBook * Library::operator[](const char * title){

ChildrenBook * m_inventory_pt = m_inventory;

for (size_t i=0; i<LIBRARY_SIZE; ++i){

if ( !strcmp(m_inventory_pt->getTitle(), title) ){ //code reuse: if check for

//specific title

return m_inventory_pt;

}

++m_inventory_pt;

}

return NULL;

}

  • Index by-Member-Value (here C-string data member m_title through interface getValid) and return Pointer-to-Data !

31 of 55

Classes - Examples

CS-202 C. Papachristos

Work with an Aggregate Class

const ChildrenBook & Library::operator[](size_t index) const {

if (index > LIBRARY_SIZE-1 ) {

return m_inventory[LIBRARY_SIZE-1];

}

else{

return m_inventory[index];

}

}

  • Index by-Array-Index and return Reference-to-Data.�All const means the method is for read-only purposes!

32 of 55

Classes - Examples

CS-202 C. Papachristos

Work with an Aggregate Class

bool Library::rentBook(const char * title, const char * name){

//code reuse: class Library operator[] overloaded for Cstring (title)

ChildrenBook * m_book_pt = (*this)[title] ;

if ( m_book_pt != NULL ){

return (*m_book_pt) + name; //code reuse: class Book operator+

//overloaded for Cstring (renter name)� }

else{

return false;

}

}

  • Re-use functionalities that should�be there according to specifications !

33 of 55

Classes - Examples

CS-202 C. Papachristos

Work with an Aggregate Class

bool Library::operator+(const ChildrenBook & childrenbook){

if ( childrenbook.valid() ){ //code reuse: first check that passed object is valid

Book * open_book_pt = findOpenSpot() ; //code reuse: then find an open spot

if ( open_book_pt ){ //code reuse: check not NULL-pointer

//if findOpenSpot() succeeded

*open_book_pt = childrenbook; //dereference and assign-to

return true;

}

}

return false;

}

  • Re-use functionalities that should�be there according to specifications !

34 of 55

Classes - Examples

CS-202 C. Papachristos

Work with an Aggregate Class

std::ostream & operator<<(std::ostream & os, const Library & l){

//Code reuse of Library's operator[]

for (int i=0; i<LIBRARY_SIZE; ++i){

if ( l[i].valid() ){

os << "Index: " << i << " has : " << l[i] << std::endl; }

}

return os; //remember: always return 1st argument for operator cascading

};

Alternative implementation ! Be careful, it’s a const Library that the function is manipulating in both cases !:

const Book * m_inventory_pt = l.m_inventory;

for (size_t i=0; i<LIBRARY_SIZE; ++i){

if ( m_inventory_pt->valid() ){ //code reuse: check that output object is valid

//call insertion operator on ostream os and pass Book object

//have to dereference m_inventory_pt

os << "Index: " << i << ", Book: " << *m_inventory_pt << endl;

}

++m_inventory_pt;

}

35 of 55

Classes - Examples

CS-202 C. Papachristos

Usage

#include <iostream>

#include <cstring>

#include "ChildrenBook.h"

using namespace std;

int main() {

Book book("Compilers!", "me");

ChildrenBook children_book(true, "Clowns!", "kid");

Book * book_Pt;

book_Pt = &book;

cout << *book_Pt << endl;

book_Pt = &children_book;

cout << *book_Pt << endl;

return 0;

}

  • Trace the output and investigate what happens in a piece of code that leverages the classes you developed in the previous steps.

  • Dynamic�Binding�perhaps?

36 of 55

Classes - Examples

CS-202 C. Papachristos

Usage

#include <iostream>

#include <cstring>

#include "Library.h"

using namespace std;

int main() {

Library library;

library + ChildrenBook(true, "Trees!");

library + ChildrenBook(false, "Hansel and Gretel", "me");

library + ChildrenBook(true, "Clowns!", "kid");

library.rentBook("Trees!", "other kid");

cout << library;

cout << Book::getIdgen() << endl; //the s_idgen static member

cout << Book::getTrash() << endl; //the s_trash static member

return 0;

}

  • Trace the output and investigate what happens in a piece of code that leverages the classes you developed in the previous steps.

37 of 55

Midterm Sample

CS-202 C. Papachristos

Question 1

void printArray(int arr[],size_t size){

for (size_t i=0; i<size; ++i)

{ cout << arr[i] << " "; }

cout << endl;

}

void fillArrayAscending(int arr[],size_t size){

for (size_t i=0; i<size; ++i)

{ arr[i] = i; }

}

const size_t ARRAYSIZE = 10;

struct MyStruct{

int intArray[ARRAYSIZE];

};

void fillStructArrayAscending(MyStruct st_in){

fillArrayAscending( st_in.intArray , ARRAYSIZE);

}

void printStructArray(MyStruct st_in){

printArray(st_in.intArray, ARRAYSIZE);

}

  • Trace output

int main(){

MyStruct my_struct;

printStructArray(my_struct);

fillStructArrayAscending(my_struct);

printStructArray(my_struct);

return 0;

}

38 of 55

Midterm Sample

CS-202 C. Papachristos

Question 1

void printArray(int arr[],size_t size){

for (size_t i=0; i<size; ++i)

{ cout << arr[i] << " "; }

cout << endl;

}

void fillArrayAscending(int arr[],size_t size){

for (size_t i=0; i<size; ++i)

{ arr[i] = i; }

}

const size_t ARRAYSIZE = 10;

struct MyStruct{

int intArray[ARRAYSIZE];

};

void fillStructArrayAscending(MyStruct st_in){

fillArrayAscending( st_in.intArray , ARRAYSIZE);

}

void printStructArray(MyStruct st_in){

printArray(st_in.intArray, ARRAYSIZE);

}

int main(){

MyStruct my_struct;

printStructArray(my_struct);

fillStructArrayAscending(my_struct);

printStructArray(my_struct);

return 0;

}

  • Trace output
  • Go line-by-line on the main !

39 of 55

Midterm Sample

CS-202 C. Papachristos

Question 1

void printArray(int arr[],size_t size){

for (size_t i=0; i<size; ++i)

{ cout << arr[i] << " "; }

cout << endl;

}

void fillArrayAscending(int arr[],size_t size){

for (size_t i=0; i<size; ++i)

{ arr[i] = i; }

}

const size_t ARRAYSIZE = 10;

struct MyStruct{

int intArray[ARRAYSIZE];

};

void fillStructArrayAscending(MyStruct st_in){

fillArrayAscending( st_in.intArray , ARRAYSIZE);

}

void printStructArray(MyStruct st_in){

printArray(st_in.intArray, ARRAYSIZE);

}

Call-by-Value implementation of fillStructArrayAscending performs actions on local copy of my_struct.

Both calls to printStructArray will print out the same (uninitialized values of my_struct).

int main(){

MyStruct my_struct;

printStructArray(my_struct);

fillStructArrayAscending(my_struct);

printStructArray(my_struct);

return 0;

}

40 of 55

Midterm Sample

CS-202 C. Papachristos

Question 2

struct MyStruct{

void printIntVar(){

cout << intVar;

}

int intVar;

};

int main(){

MyStruct ms;

ms.intVar = 1;

ms.printIntVar();

return 0;

}

class MyClass{

public:

void setIntVar(int v){

m_intVar = v;

}

void printIntVar(){

cout << m_intVar;

}

private:

int m_intVar;

};

int main(){

MyClass mc;

mc.setIntVar(1);

mc.printIntVar();

return 0;

}

  • Check compilation correctness

41 of 55

Midterm Sample

CS-202 C. Papachristos

Question 2

struct MyStruct{

void printIntVar(){

cout << intVar;

}

int intVar;

};

int main(){

MyStruct ms;

ms.intVar = 1;

ms.printIntVar();

return 0;

}

class MyClass{

public:

void setIntVar(int v){

m_intVar = v;

}

void printIntVar(){

cout << m_intVar;

}

private:

int m_intVar;

};

int main(){

MyClass mc;

mc.setIntVar(1);

mc.printIntVar();

return 0;

}

  • Check compilation correctness
  • Check every function for known rules (e.g. access specifications, type correctness, overload resolution, etc.)

42 of 55

Midterm Sample

CS-202 C. Papachristos

Question 2

struct MyStruct{

void printIntVar(){

cout << intVar;

}

int intVar;

};

int main(){

MyStruct ms;

ms.intVar = 1;

ms.printIntVar();

return 0;

}

class MyClass{

public:

void setIntVar(int v){

m_intVar = v;

}

void printIntVar(){

cout << m_intVar;

}

private:

int m_intVar;

};

int main(){

MyClass mc;

mc.setIntVar(1);

mc.printIntVar();

return 0;

}

All clear.

We can have in a struct :

  1. Member functions
  2. Constructors
  3. Destructor

and struct members default to public.

43 of 55

Midterm Sample

CS-202 C. Papachristos

Question 3

class TestClass{

TestClass(){

cout << m_intTest;

}

TestClass(int intTest){

m_intTest = intTest;

cout << m_intTest;

}

private:

int m_intTest;

};

int main(){

TestClass tc(1000);

return 0;

}

  • Check compilation correctness
  • Trace output

44 of 55

Midterm Sample

CS-202 C. Papachristos

Question 3

class TestClass{

TestClass(){

cout << m_intTest;

}

TestClass(int intTest){

m_intTest = intTest;

cout << m_intTest;

}

private:

int m_intTest;

};

int main(){

TestClass tc(1000);

return 0;

}

  • Check compilation correctness
  • Check every function for known rules (e.g. access specifications, type correctness, overload resolution, etc.)
  • Trace output

45 of 55

Midterm Sample

CS-202 C. Papachristos

Question 3

class TestClass{

TestClass(){

cout << m_intTest;

}

TestClass(int intTest){

m_intTest = intTest;

cout << m_intTest;

}

private:

int m_intTest;

};

int main(){

TestClass tc(1000);

return 0;

}

No public access specifier for class Constructors.

Class members default to private.

46 of 55

Midterm Sample

CS-202 C. Papachristos

Question 4

class StaticClass{

public:

static size_t count;

StaticClass(){

m_count = 0;

count++;

}

StaticClass(int count_in){

m_count = count_in;

count++;

}

void countUp(){ m_count++; }

int getCount(){ return m_count; }

private:

int m_count;

};

int StaticClass::count = 0;

int main(){

StaticClass sc_a;

sc_a.countUp();

StaticClass sc_b(sc_a.count);

sc_b.countUp();

StaticClass sc_c(sc_b);

sc_c.countUp();

cout << sc_a.getCount() <<" "<<

sc_b.getCount() <<" " <<

sc_c.getCount() <<" " <<

StaticClass::count << endl;

return 0;

}

  • Trace output

47 of 55

Midterm Sample

CS-202 C. Papachristos

Question 4

class StaticClass{

public:

static size_t count;

StaticClass(){

m_count = 0;

count++;

}

StaticClass(int count_in){

m_count = count_in;

count++;

}

void countUp(){ m_count++; }

int getCount(){ return m_count; }

private:

int m_count;

};

int StaticClass::count = 0;

int main(){

StaticClass sc_a;

sc_a.countUp();

StaticClass sc_b(sc_a.count);

sc_b.countUp();

StaticClass sc_c(sc_b);

sc_c.countUp();

cout << sc_a.getCount() <<" "<<

sc_b.getCount() <<" " <<

sc_c.getCount() <<" " <<

StaticClass::count << endl;

return 0;

}

  • Trace output
  • Go line-by-line on the main !

48 of 55

Midterm Sample

CS-202 C. Papachristos

Question 4

class StaticClass{

public:

static size_t count;

StaticClass(){

m_count = 0;

count++;

}

StaticClass(int count_in){

m_count = count_in;

count++;

}

void countUp(){ m_count++; }

int getCount(){ return m_count; }

private:

int m_count;

};

int StaticClass::count = 0;

int main(){

StaticClass sc_a;

sc_a.countUp();

StaticClass sc_b(sc_a.count);

sc_b.countUp();

StaticClass sc_c(sc_b);

sc_c.countUp();

cout << sc_a.getCount() <<" "<<

sc_b.getCount() <<" " <<

sc_c.getCount() <<" " <<

StaticClass::count << endl;

return 0;

}

No Copy-Constructor overload manipulating the m_count static, like the other Constructors do.

Carefully mind the sequence of actions!

49 of 55

Midterm Sample

CS-202 C. Papachristos

Question 5

class BaseClass{

public:

void setIntVar(int i){ m_intVar = i; }

int getIntVar(){ return m_intVar; }

private:

int m_intVar;

};

class DerivedClass : public BaseClass{

public:

void setDoubleVar(double d){

m_doubleVar = d * m_intVar;

}

double getDoubleVar(){

return m_doubleVar;

}

private:

double m_doubleVar;

};

int main(){

BaseClass b_result;

BaseClass b1;

b1.setIntVar(10);

DerivedClass d2;

d2.setDoubleVar(2.5);

b_result.setDoubleVar((double)b1.getIntVar() + d2.getDoubleVar());

cout << b_result.getDoubleVar();

return 0;

}

  • Check compilation correctness

50 of 55

Midterm Sample

CS-202 C. Papachristos

Question 5

class BaseClass{

public:

void setIntVar(int i){ m_intVar = i; }

int getIntVar(){ return m_intVar; }

private:

int m_intVar;

};

class DerivedClass : public BaseClass{

public:

void setDoubleVar(double d){

m_doubleVar = d * m_intVar;

}

double getDoubleVar(){

return m_doubleVar;

}

private:

double m_doubleVar;

};

int main(){

BaseClass b_result;

BaseClass b1;

b1.setIntVar(10);

DerivedClass d2;

d2.setDoubleVar(2.5);

b_result.setDoubleVar((double)b1.getIntVar() + d2.getDoubleVar());

cout << b_result.getDoubleVar();

return 0;

}

  • Check compilation correctness
  • Check every function for known rules (e.g. access specifications, type correctness, overload resolution, etc.)

51 of 55

Midterm Sample

CS-202 C. Papachristos

Question 5

class BaseClass{

public:

void setIntVar(int i){ m_intVar = i; }

int getIntVar(){ return m_intVar; }

private:

int m_intVar;

};

class DerivedClass : public BaseClass{

public:

void setDoubleVar(double d){

m_doubleVar = d * m_intVar;

}

double getDoubleVar(){

return m_doubleVar;

}

private:

double m_doubleVar;

};

int main(){

BaseClass b_result;

BaseClass b1;

b1.setIntVar(10);

DerivedClass d2;

d2.setDoubleVar(2.5);

b_result.setDoubleVar((double)b1.getIntVar() + d2.getDoubleVar());

cout << b_result.getDoubleVar();

return 0;

}

  • Derived-Class Methods called on Base-Class Object.
  • Access of private (not protected in Derived Class)

52 of 55

Midterm Sample

CS-202 C. Papachristos

Question 6

class Parent{

public:

virtual void setValue(int value){ m_value = value; }

virtual int getValue(){ return m_value; }

protected:

int m_value;

};

class Child : public Parent{

public:

virtual void setValue(int value){

m_precisionValue = value;

}

virtual double getValue(){

return m_precisionValue;

}

private:

double m_precisionValue;

};

int main(){

Child c;

c.setValue(1);

cout << c.getValue()/2 << endl;

return 0;

}

  • Check compilation correctness – Worst Case Scenario

53 of 55

Midterm Sample

CS-202 C. Papachristos

Question 6

class Parent{

public:

virtual void setValue(int value){ m_value = value; }

virtual int getValue(){ return m_value; }

protected:

int m_value;

};

class Child : public Parent{

public:

virtual void setValue(int value){

m_precisionValue = value;

}

virtual double getValue(){

return m_precisionValue;

}

private:

double m_precisionValue;

};

int main(){

Child c;

c.setValue(1);

cout << c.getValue()/2 << endl;

return 0;

}

  • Check compilation correctness – Worst Case Scenario
  • Check every function for known rules (e.g. access specifications, type correctness, overload resolution, etc.)

54 of 55

Midterm Sample

CS-202 C. Papachristos

Question 6

class Parent{

public:

virtual void setValue(int value){ m_value = value; }

virtual int getValue(){ return m_value; }

protected:

int m_value;

};

class Child : public Parent{

public:

virtual void setValue(int value){

m_precisionValue = value;

}

virtual double getValue(){

return m_precisionValue;

}

private:

double m_precisionValue;

};

int main(){

Child c;

c.setValue(1);

cout << c.getValue()/2 << endl;

return 0;

}

Overriding a virtual Method with a non-Covariant type returning function.

55 of 55

Time for Questions !

CS-202

CS-202 C. Papachristos