C++ Objects Structs and Classes Presented by: Brian Lojeck 4/25/2011 ET286, Prof. Hill

Preview:

Citation preview

C++ ObjectsStructs and Classes

Presented by: Brian Lojeck4/25/2011

ET286, Prof. Hill

The Sin Wave

• To properly describe a sin wave:– Amplitude– Period– Phase offset– DC offset

• Suppose we wanted to store data for many sin waves at once?

The old way?

double Wave1Amp, Wave2Amp, Wave3Amp…double Wave1Period, Wave2Period, Wave3…double Wave1Phase, Wave2Phase, Wave3…double Wave1DC, Wave2DC, Wave3DC…

Slightly Better…

double Amplitudes[3];double Periods[3];double PhaseOffsets[3];double DCOffsets[3];

Problems

• Related data is not kept together– Amp[0] goes with Period[0] with DC[0]

• Multiple arrays to pass back and forth in functions

• Leads to messy code that can be complex to read and problem-solve

A Struct is One Solution

• Is a data type created by the programmer

• Contains any number of different data elements, of any type desired– “Member Data” or

“Data Members”

To Declare A Struct

struct Sin_Wave {

int SampleCount;double Amplitude;double Period;double Phase;

};

To Instantiate A Struct

struct Sin_Wave {int SampleCount; double Amplitude;double Period; double Phase;

};

int main() {int Counter1, Counter2;Sin_Wave SampledSinWave;Sin_Wave OutputSinWave[10];

}

To Access A Struct’s Member Data

int main() {Sin_Wave SampledSinWave;Sin_Wave OutputSinWave[10];

SampledSinWave.Amplitude=4;cout << OutputSinWave[2].Period;

}

Beyond Structs

• Structs allow for useful data types to be created as needed

• Data types are often less important then the functions that operate on the data

• If the functions are properly written, the data itself does not ever need to be directly accessed by the programmer

Classes

• Classes– Contain any desired data types, like a struct– Also contain the functions that operate on the

data• Called “Member Functions” or “Methods”• The two terms are interchangeable

– The data is typically “private”, and not accessible to the programmer directly

– The Methods are typically the only public (accessible to the programmer) interface

To Program A Classclass CRectangle { private:

int Height, Width; //has data members just like a struct public:

void set_values (int,int);int area () {return (Height*Width);}

};

void CRectangle::set_values (int a, int b) { Height = a; Width = b; }

int main() {…

To Instantiate A Classclass CRectangle { private:

int Height, Width; //has data members just like a struct public:

void set_values (int,int);int area () {return (Height*Width);}

};

int main() {CRectangle BigRectangle, SmallRectangle;CRectangle LottaRectangles[100];

}

get() and set()

• The most common functions in a c++ class are get() and set()– set() lets the programmer ENTER data into a class

• void setHeight(int)• void setGrade(char)

– get() lets the programmer EXTRACT data• int getHeight()• char getGrade()

– Functions like this are REQUIRED if the data member is private

– These functions MUST be public to be used

To Access A Class’s Dataclass CRectangle { private: int Height, Width; public: void set_values (int,int); int get_Height () {return (Height);} };

int main() {CRectangle BigRectangle, SmallRectangle;CRectangle LottaRectangles[100];

BigRectangle.Height=100; // FAILSBigRectangle.set_Height(100); //WORKScout << BigRectangle.Height; //FAILScout << BigRectangle.get_Height(); //WORKS

}

WHY?

• Allowing a programmer to access data directly means:– Student.Grade=‘Q’;

• Requiring a set function lets you check for errors (or malicious hacking attempts) and prevent them from ruining the system

Coding Example

class Date {private:

int Month, Day, Year;public:

void setMonth(int);void setDay(int);void setYear(int);int getMonth();int getDay();int getYear();

};

Coding Example

int Date::getMonth(){return(Month);

}

int Date::getYear(){return(Year);

}

int Date::getDay(){return(Day);

}

Coding Example

void Date::setMonth(int m){if (m<=12 && m>=1) {

Month=m;}else {

Month=0;}return;

}

Coding Example

void Date::setDay(int d){if (d<=31 && d>=1) {

Day=d;}else {

Day=0;}return;

}

Coding Example

void Date::setYear(int y){

if (y<100) y+=2000;

if (y<10000) Year=y;else Year=0;

return;}

Coding Example

int main(){Date Tdy;Tdy.setDay(13); Tdy.setYear(2011); Tdy.setMonth(4);cout << “Today is: “ << Tdy.getMonth() << “/” << Tdy.getDay() << “/” << Tdy.getYear() << endl;return 0;

}

Constructor

• When you instantiate a class, the data contained inside is un-initialized

• Similar to when you instantiate native data types:– int j; // j can contain any random value– int j=0; //j is initialized cleanly to 0

• A Constructor lets you provide initialization values to the class

• A Constructor is… A TYPE OF SET() FUNCTION

A Constructor

• Is called once, and only once, when you instantiate the class:– MyStudentClass BrianL; // It just got called

• Writing your own constructor lets you assign default values or enter your own values– MyStudentClass BrianL; //Legal constructor– MyStudentClass BrianL(“Brian”,”F”); //also legal

Coding A Constructor

class MyClass{int i;

public:MyClass(); //default constructorMyClass(int); // another constructorset_i(int); // a set function

};

Coding A Constructor

MyClass::MyClass(){set_i(0);}

MyClass::MyClass(int newAye){set_i(newAye);}

MyClass::set_i(int newAye){i=newAye;}

Using The Constructor

int main(){MyClass Counter; //legal, Counter.i==0MyClass Class2(30); //Class2.i==30Counter.set_i(31); //set functions work tooreturn 0;

}

Organization Of Objects In Files

• There is no physical reason you cannot describe a class, define the class, and use it in a program’s main() function all in one file.

• This is a bad habit to get into, it will make larger programs appear disorganized and hard to edit/correct/change.

Organization Of Objects In Files

• Class definitions are typically organized:– Class description in a header file (ClassName.h)– Class definition in a c++ code file (ClassName.cpp)– The .h file is included in the main program’s file

using the include directive• #include “ClassName.h”

– All files related to a class should be named after the class for organization purposes

Create A Header File

Create A Header File

Create A Header File

Header File Contents

Create The Definition .cpp File

Create The MyClass.cpp File

MyClass.cpp File Contents

MyClass.cpp File Contents

Main *.cpp File Contents

Recommended