DOC PREVIEW
Saddleback CS 1C - Class Constructors & Static Class Members

This preview shows page 1-2-3 out of 8 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 8 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 8 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 8 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 8 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

CS1C – Advanced Programming in C++Saddleback College Fall 2011 – J TateyamaClass Constructors & Static Class MembersChapter 4CS1C – Saddleback College Inline Functions In CS 1B we wrote a lot of very small value-returning functions to return an average, the smaller of two numbers etc. These functions typically contained a small expression. There are benefits and drawbacks to defining functions to do small operations. Benefits–Function calls make a program easier to read and understand–Changes to functions are reflected everywhere in a program–Function can be use in any application without rewritingDrawbacks–Calling a function is slower than executing an expression–When a function is called, arguments must be copied, program must branch to a new location, and return address must be copied Overhead associated with function calls can be reduced by using inline functionsCS1C – Saddleback College Inline Function Exampleinline bool Empty(DataPtr head){return head == NULL;} The above declaration requests that the function be expanded "in line" everywhere a call appears in the program. The callif(Empty(head))cout << "Stack is empty";would be expanded during compilation time toif( head == NULL )cout << "Stack is empty";The use of inline is meant to optimize small functions that are called frequently. Note: The inline specification is a request to the compiler. The compiler may choose to ignore this requestCS1C – Saddleback CollegeClass ReviewClass – defines the variables and methods common to objects of a given type. The class provides the blueprint or prototype for the objects. An object is an instance of a class. instance methodsinstance variablesobject (instance of a class)class Rectangle{public: Rectangle( ); Rectangle(float l, float w); float GetLength( ) const; float GetWidth( ) const;private: float recLength; float recWidth;};void main( ) Rectangle recOne;}{CS1C – Saddleback CollegeClass Components ReviewClass Members–data, functions (methods) and type definitions (typedef) –By default all members of a class are private–Member access specifiers must be used to allow access •public•private•protectedMember Functions (methods)–must be declared inside the class–may be defined inside the class (inline)–may be declared as const–when defined outside the class they must use scope resolution•className::methodName(){…}CS1C – Saddleback CollegeClass ConstructorsA member function that is automatically invoked whenever a class object is createdGuarantees the initialization of a class objectMust have the same name as the classNot a void or value returning functionNot invoked using the dot notationMay be overloaded to allow several ways for the data members to be initializedNote: tilde (~classname) is called the destructor and is used to release memoryCS1C – Saddleback CollegeClass Exampleclass Time// Time is in military format{public:Time( ); // default constructorTime(int h, int m, int s); // overloaded constructor with 3 parametersvoid SetTime(int h, int m, int s);void OutputTime() const;void OutputTimeStd() const;void IncrementTime();private:int hour;int minute;int second;};CS1C – Saddleback CollegeInvoking ConstructorsThere are two ways a constructor is invoked. Example – given class TimeImplicit (when object is instantiated)–Time t1, t2(2,35,10), t3;–Object t1 will be set to 0's, t2 will be 2:35:10, and t3 will be set to 0'sExplicit (valid only after object is instantiated)–t1=Time();–t2=Time(2,35,10);–t3=Time(1,30,00);CS1C – Saddleback CollegeConstructor GuidelinesClass should always contain default constructorIf the only constructor you specify requires parameters, and the client fails to send them, the compiler will not create a default constructor for you. This will result in a compilation error.Compiler chooses constructor based on number of arguments and their data typesIf default constructor should not do any initialization then still include it in your implementation file but leave the body empty–Time::Time(){ }Arguments are passed by placing them after the name of the class object being declared–Time time2(10,15,30);CS1C – Saddleback CollegeInitializer ListsConstructors consist of a name, parameter list and body just like functions Initializer lists may also be used to initialize the data members of a class using the class constructorUsed in place of statements in the constructor bodyInitialization then becomes part of the heading for the class constructorProvides means of accessing the constructors for base classes also –More on this when we discuss inheritance next week–This is a very important point to rememberCS1C – Saddleback CollegeInitializer Lists - Example with variablesTime::Time(int h, int m, int s){hour = h;minute = m;second = s;}Can be replaced by Time::Time(int h, int m, int s) : (hour(h),minute(m),second(s)){}Note the proper placement of the “:” and the empty body {}CS1C – Saddleback CollegeInitializer Lists - Example with ConstantsTime::Time(int h, int m, int s){hour = 0;minute = 0;second = 0;}Can be replaced by Time::Time(int h, int m, int s) : (hour(0),minute(0),second(0)){}Note: This constructor can not be used in the same class as the previous constructor since they both have the same signature- returns Time- parameters – 3 intsCS1C – Saddleback CollegeInitializer Lists Example with ValidationTime::Time(int h, int m, int s) : hour ((h >= 0 && h <= 23) ? h : 0), minute ((m>=0 && m <= 59) ? m : 0), second ((s>=0 && s <= 59) ? s : 0){ } Edits the parameter values for h, m, s and if not valid then set to 0.Same as:if (h >= 0 && h <=23) (expression)? hour = h; value if trueelse hour = 0; value if falseCS1C – Saddleback CollegeInitialization ReviewWhen a variable is declared and no initial value is specified, the initial value, if any, depends on the type of the variable and where it is declaredBuilt-In Types:–Variables declared in global scope (outside all blocks) are initialized to their default value–Variables declared inside a function body are not initializedIf an initializer list is not provided for a class member the compiler uses the default constructor for that memberIf the member’s class does not have a default constructor then initialization failsCS1C – Saddleback


View Full Document
Download Class Constructors & Static Class Members
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Class Constructors & Static Class Members and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Class Constructors & Static Class Members 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?