Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSCE 3110 Data Structures & Algorithms C++ warm-up.

Similar presentations


Presentation on theme: "CSCE 3110 Data Structures & Algorithms C++ warm-up."— Presentation transcript:

1 CSCE 3110 Data Structures & Algorithms C++ warm-up

2 C++ Warm-up History What is C++ How does C++ relate to other OO languages Types of applications for C++ Advantages / Disadvantages of C++

3 History of C++ 1972: C language developed at Bell Labs Dennis Ritchie wrote C for Unix OS Needed C for work with Unix late 70s: C becomes popular for OS development by many vendors Many variants of the language developed ANSI standard C in 1987-89

4 History of C++ (continued) early 80s: Bjarne Stroustrup adds OO features to C creating C++ 90s: continued evolution of the language and its applications preferred language for OS and low level programming popular language for application development low level control and high level power

5 Conceptually what is C++ Alternatives: is it C, with lots more options and features? is it an OO programming language with C as its core? is it a development environment? On most systems it is a development environment, language, and library, used for both procedural and object oriented programming, that can be customized and extended as desired

6 Versions of C++ ANSI C++ Microsoft C++ (MS Visual C++ 6.0) Other vendors: Borland, Symantec, Turbo, … Many older versions (almost annual) including different version of C too Many vendor specific versions Many platform specific versions For this class: Unix / Linux based versions g++

7 Characteristics of C++ as a Computer Language Procedural Object Oriented Extensible...

8 Other OO Languages Smalltalk pure OO language developed at PARC Java built on C/C++ objects and data types Eifel and others

9 What you can do with C++ Apps (standalone, Web apps, components) Active desktop (Dynamic HTML, incl Web) Create graphical apps Data access (e-mail, files, ODBC) Integrate components w/ other languages

10 Disadvantages of C++ Tends to be one of the less portable languages Complicated? 40 operators, intricate precedence, pointers, etc. can control everything many exceptions and special cases tremendous libraries both standard, vendor specific, and available for purchase, but all are intricate Aspects above can result in high maintenance costs

11 Advantages of C++ Available on most machines Can get good performance Can get small size Can manage memory effectively Can control everything Good supply of programmers Suitable for almost any type of program (from systems programs to applications)

12 Basics of C/C++: Topics to Cover Basic types Operators Flow control Classes Inheritance

13 Primitive Types booltrue or false (only C++) char8/16-bit short 16-bit signed integer int32-bit signed integer unsigned32-bit unsigned integer long32 / 64-bit signed integer float32-bit floating point double64-bit floating point

14 Operators and Precedence []. to access arrays elements / to access object methods and fields expr++ expr-- ++expr --expr ! new (type)expr * / % + - > (integers only) >= <= == != &

15 Operators and Precedence ^ | && (booleans only) || (booleans only) ?: = += -= *= …. C++ allows operator overloading

16 Precedence Example What is: 5 + 21 / 4 % 3 = 5 + (21 / 4) % 3 = 5 + ( 5 % 3) = 5 + 2 = 7

17 Explicit Casting (type) expression Possible among all integer and float types Possible among some class references E.g. int i = (int) ( (double)5 / (double)3 )

18 Implicit Casting Applied automatically provided there is no loss of precision float  double int  double Example int iresult, i=3; double dresult, d=3.2; dresult = i/d => implicit casting dresult=0.9375 iresult = i/d => error! Why? Loss in precision, needs explicit casting

19 Control Flow if (boolean) statement; else if(boolean) statement2; else statement3; Booleans only, not integers! if (i > 0)  legal if (i = 2)  legal / illegal ?

20 Switch / case switch (controlVar) { case 'a' : statement-1 break; case 'b' : statement-2 break; default : statement-3 break; } Do not forget the break command to avoid surprise result!

21 Loops while( ) statement; do statement; while( ) for(init-expr; ; incr-expr) statement;

22 Loop Refresher Which loops must execute their statements at least once? Which loops can choose to never execute their statements? Which value of the boolean indicates to do the statements again?

23 Value vs. Reference Variables Variables of primitive types are value variables Variables of arrays or classes are reference variables 10 i int i =10; j 10 int * j = new int[1]; j[0] = 10; new performs dynamic memory allocation

24 Passing Parameters All parameters in C/Java are passed “by value” C++ allows for three different ways of passing parameters: Pass “by value” E.g. foo (int n) Appropriate for small objects (usually primitive types) that should not be altered by the function call Pass “by constant reference” E.g. foo(const T& myT) Appropriate for large objects that should not be altered by the function call Pass “by reference” E.g. foo(bool & errFlag) Appropriate for small objects that can be altered by the function call Array types are always passed “by reference”

25 Arrays Refer to several values of the same type Create new array int* myArray = new int[20]; Index from 0 to length-1 Delete an array delete [] myArray;

26 Classes in C++: Why Create Classes / Objects? Keeps all related info (i.e., data) together Refer to all the related info by one name Protect the information Hide methods that use or change the info Keep methods together with their related info

27 Example of Benefits of Creating an Object Keeps all related info (i.e., data) together Person thisPerson; Person thisPerson = new Person ("Bill", "Clinton", 52, Person.MALE); Refer to all the related info by one name thisPerson Protect the information lastName = "Dole"; //normally data members are private, and member functions are public

28 Example of a Simple Class class Change { private: int quarters; int dimes; public: int getQuarters() {return quarters;} int getDimes() {return dimes;} void setQuarters(int aQuarters) {quarters = aQuarters;} …... void printChange() {cout << "\nQuarters: " << quarters << " Dimes: " << dimes << endl; } };

29 Instantiating an Object The class definition does not create any objects Instantiating and constructing are equivalent words for building a new object based on the model (i.e., template) of the class Instantiating is done just like declaring a variable of a built in data type Instantiating is done by a constructor (sometimes called a constructor method) If the "class provider" does not provide a constructor, then the C++ compiler provides a default one automatically The default constructor does not provide values to the data members (i.e. the instance variables)

30 Instantiating an Object (more) When the object is instantiated, memory is allocated Example of instantiation (implicit call of constructor) Car myCar; Elephant oneElephant, twoElephant; No initialization takes place Each object has its own memory allocation oneElephant and twoElephant are separate objects in different locations in memory Each is addressed individually by name or location Each data member is addressed individually using the object name and the data member name, for example: oneElephant.age twoElephant.name

31 Referencing an Object Each object has a name (or a location) which is assigned when the object is instantiated private data members are accessible only within the class since most data members are private, that means that these data items are accessed generally by means of member functions myElephant.age = 72; //won't work, assuming age //is declared as private myElephant.setAge(72); // will work

32 Defining the Member Function Outside the Class int main() { …. } //end of main function //DEFINE MEMBER FUNCTION OUTSIDE THE CLASS void Change::addChange(Change myChange) //global scope resolution { quarters += myChange.quarters; //can refer to data members directly dimes += myChange.dimes; pennies += myChange.pennies; } …. //another member function definition here

33 Invoking or Calling the Member Function //MAIN int main(void) { //declare two Change objects Change firstChange, secondChange;//constructs the objects firstChange.setQuarters(2);//calls member function for object secondChange.setDimes(8);//calls member function for different object firstChange.printChange(); firstChange.addChange(secondChange); //add the amounts together cout << "amounts added together: "; //print out firstChange firstChange.printChange(); } //end of main

34 Inheritance The power of object-oriented languages Enables reuse of fields/methods All parent fields included in child instantiation Protected and public fields and methods directly accessible to child Parent methods may be overridden New fields and methods may be added to the child Multiple inheritance

35 Inheritance (cont’d) class classname: public parentname { private: ….; public: ….; //access to parent methods through // parentname::methodname … }

36 Finally: Some Conventions for Variable Names Use letters and numbers Do not use special characters including spaces, dots, underlines, pound signs, etc. The first letter will be lower case Use variable names that are meaningful (except for occasional counters that we might call i, j, x, etc.) You can concatenate words, and capitalize each after the first, e.g., bankBal, thisAcctNum, totAmt If you abbreviate, be consistent. For example do not use both bankBal and totalBalance as variable names.

37 Some Conventions for Struct and Class Names In creating names of structs and classes, apply the same rules as for variable names, except the first character will be upper case Example: an object's name: myCar the struct or class name: Car Another Example: aPerson and Person


Download ppt "CSCE 3110 Data Structures & Algorithms C++ warm-up."

Similar presentations


Ads by Google