Presentation is loading. Please wait.

Presentation is loading. Please wait.

G52CFJ C/C++ for Java Programmers Lecture 13

Similar presentations


Presentation on theme: "G52CFJ C/C++ for Java Programmers Lecture 13"— Presentation transcript:

1 G52CFJ C/C++ for Java Programmers Lecture 13
Constructors Inline functions Class members References CW2 initial comments

2 Last lecture : structs and unions
structs can have empty space in them Array elements appear one after another in memory struct packing will aim for fast access Putting in empty space to align things on two or four (or more) byte boundaries for fast access struct elements appear one after another in memory, but may have gaps union elements are all in the same place If there is no extra space in the packing then you can calculate the struct size (total of contents) or union size (maximum size of contents)

3 Last lecture : C++ Intro
Much is the same – with many additions Some differences in style of doing things Different header file names e.g. cstdio not stdio.h You can add functions to structs (as members) Use the . operator to access member functions (as for data) #include <cstdio> struct Print { void print() printf( "Test\n" ); } }; int main() Print p; p.print();

4 Reminder: public vs private
class/struct members can be public or private Or protected (lecture 14) structs vs classes Differ only in default access classes default to private access structs default to public access You can treat structs as C structs as long as you avoid some of the C++ only features class DemoClass { public: int GetValue() return m_iValue; } void SetValue(int iValue) m_iValue = iValue; private: int m_iValue; };

5 This lecture Constructors Inline functions
Function definitions outside the class declaration References (weak pointers) Comments on CW2 structure

6 Creating objects (on the stack)
For the moment we will consider only objects on the stack Non-existent in Java – Java uses new This way I can leave the new operator until later The same syntax can be used as for structs in C: struct ListItem item1; DemoClass myDemoClass; In C++ you can omit the keyword ‘struct’ Arrays of objects (of type DemoClass): DemoClass myDemoArray[4];

7 Constructors and destructors

8 Constructors and Destructors
Called when an object is created Has function name same as class name And no return type (none/empty, NOT void!) Adding a constructor makes it impossible to provide a C-style initialiser. e.g. = {0,1,2}; No constructor => you can use C initialised Destructor (similar to Java finalize) Called when an object is destroyed Is a function with name ~ then class name And no return type

9 Example C++ class class DemoClass Constructor { No return type public:
{ } ~DemoClass() int GetValue() const { return m_iValue; } void SetValue( int iValue ) { m_iValue = iValue; } private: int m_iValue; }; Constructor No return type Accessor Access only, no changes Ideally label the function with keyword ‘const’ (see also lecture 16) Destructor No return type Mutator. Mutates/changes the object Data member/member variable/attribute

10 Constructor parameters
You can pass parameters to constructors You can have multiple constructors Which differ in which parameter types they expect The compiler will consider which parameters are passed to determine which constructor to use In the same way as functional overloading You are probably used to this in Java Note: It’s a general C++ rule that, if your code introduces ambiguity (i.e. could do A or B) then it will not compile The types of the parameters will determine which constructor is called. If it is ambiguous, the code will not compile!

11 Passing parameters to constructors
Create a constructor which takes parameters e.g. a constructor which takes an int: DemoClass(int iValue) { … } // In class DemoClass To create an object on the stack, passing values to constructor use: DemoClass myDemoClass(4);

12 Default Constructor The ‘Default Constructor’ is a constructor which can be called with no parameters e.g. one which has no parameters or has default values for all parameters A class can only have one default constructor When you create arrays, the default constructor is used (because no parameters are provided): e.g.: DemoClass myDemoArray[4];

13 Parameters or not? Create an object, using default constructor
DemoClass myDemoClass1; Or create an object, passing values to the constructor (selects the constructor to use) DemoClass myDemoClass3( "Temp" ); IMPORTANT: Do NOT add empty brackets (), when constructing on the stack, if there are no parameters! Cannot identify that you are not declaring a function e.g. DemoClass myDemoClass1(); // WRONG!!!

14 Defaulting parameters
In C++, parameters can have default values So can parameters in constructors Use the ‘= <value>’ syntax following the parameter declaration e.g.: DemoClass( char* dummy, int iValue = -1) {} Will match the following: DemoClass myDemoClass3( "Temp", 3 ); DemoClass myDemoClass4( "Temp" ); Default values appear only in the function declaration, not any separate definition

15 Basic types Basic types can be initialised in the same way as classes (using the brackets) Create an int (we have seen this a lot) int iVal = 4; // Initialisation! The () form can also be used for basic types int iVal(4); // Initialisation! Both do exactly the same thing

16 Member data initialisation
Member data is NOT always initialised Default constructor is called for members of type class/struct unless you say otherwise Basic types and pointers (e.g. int, short or char*) are NOT initialised You should always initialise them BIG WARNING TO YOU!!!! (from me, because compiler won’t warn you)

17 Initialisation list, comma separated
Initialisation list allows you to call other constructors By passing values to the constructor This includes base classes (next week) And data members Uses the () form of initialisation i.e. initialisation parameters to use are inside () Uses the : operator following the constructor parameters (before the opening brace): DemoClass(int iValue) : m_iValue(iValue) {} Initialisation list, comma separated

18 Initialisation vs assignment
With an int type data member called m_iValue Compare the following: DemoClass(int iValue) : m_iValue(iValue) {} With the following: { m_iValue = iValue; } Question: Are these the same?

19 Initialisation vs assignment
First case: DemoClass(int iValue) : m_iValue(iValue) {} m_iValue is initialised with value iValue Second case: { m_iValue = iValue; } m_iValue is created but not initialised then the value of iValue is assigned to it If it was an object (of type struct/class) then it would be initialised using default constructor then assigned i.e. value is set twice!

20 More on initialisation lists
Compare the following: 1) int i = 4; // Initialisation 2) int j; // Uninitialised j = 4; // Assignment Initialisation lists are used a LOT in C++ Should be used by preference to member assignment Not available in Java! In Java you use super() to pass parameters to base class constructor, and then just assign values to members in the constructor In C++ you use the initialisation list for both C++’s way is faster in some cases (and never slower) Avoids work from an unnecessary default constructor

21 Inline functions and member functions and data

22 Inline functions Inline functions act like normal functions
BUT the compiler will try to put the code ‘inline’ (in the caller function) instead of as a function call Use the keyword ‘inline’ inline int max( int a, int b ) { return a>b ? a : b; } printf("%d\n", max(12,34) ); Similar to a ‘safe’ macro expansion Safely replaces the function call with the code Unlike a macro (#define) Avoids the overhead of creating a stack frame Has to be included in EVERY file which uses it VERY useful for small, fast functions Advice only: compiler can decide NOT to inline code

23 Function definitions ‘outside’ the class
Member functions are usually defined outside of the class declaration In Java they are always defined within the class declaration, with one class per file Defining functions within the class declaration implicitly makes them inline As if they had ‘inline’ on them In C++ you usually have: Function declaration inside class declaration Function definition somewhere else With a ‘label’ to say it is a class member We use the scoping operator :: to label it Reason: allows hiding of the implementation Good program design, that Java’s policy makes very hard to do

24 Defining class member functions
DemoClass.h DemoClass.cpp class DemoClass { public: DemoClass( int iValue = -1); ~DemoClass(); int GetValue(); void SetValue( int iValue); private: int m_iValue; }; #include "DemoClass.h" DemoClass::DemoClass( int iValue ) : m_iValue(iValue) { … } DemoClass::~DemoClass() int DemoClass::GetValue() { return m_iValue; } void DemoClass::SetValue( { m_iValue = iValue; }

25 The this pointer An object is a collection of data (its state)
A class defines the structure of the object and what you can do with it (a design for an object) e.g. Clothing, cars, programs, etc For functions to actually do something, they need to know which object to act on (Non-static) member functions have an implicit extra parameter saying which object to act on Parameter type is a pointer to object (of correct class) And the parameter name is this Note: as you know, this exists in Java too! As an object reference to the current object

26 The this pointer GetValue() is effectively: DemoClass* this )
int GetValue( DemoClass* this ) SetValue(int) is effectively: void SetValue( DemoClass* this, int iValue ) Can refer to m_iValue as this->m_iValue Not obvious because you can miss out the this-> class DemoClass { public: int GetValue() return m_iValue; } void SetValue( int iValue) m_iValue = iValue; private: int m_iValue; };

27 Static methods and attributes
static members are shared between all objects of that class NOT associated with a specific object Just like static in Java Static member functions do not have a this pointer Both static and non-static member data and functions are class members i.e. They have access to private members class MyClass { public: static int var; static void foo(); }; int MyClass::var = 25; void MyClass::foo() var = 32; } int main() MyClass::var = 15; MyClass::foo();

28 Exercises (in prep for CW2)

29 This week’s exercises See here (from last week):
Ensure that you go through the Using Visual Studio 2008 instructions Go through the sample and explanation SDL_Demo_C_v1.0_bouncing_ball.pdf Go through the second walkthrough – note the function pointers, and new implementations of the custom functions

30 Understand what these functions do:
(See custom.c, all are named custom…) Initialise and Deinitialise SetupBackgroundBuffer DrawScreen DrawChangingObjects GetUpdateRectanglesForChangingObjects GameAction KeyDown and KeyUp CW2: These are the functions you implement Look at the implementations for the bouncing ball and Pong, it will help you later

31 Notice the functions that you call:
Know what these functions do (not how they do it) (See basegame.h for declarations) Draw to screen SetScreenPixel, SafeSetScreenPixel DrawString Draw to background SetBackgroundPixel, FillBackground CopyAllBackgroundBuffer, CopyBackgroundPixels Record which parts of screen change GetNextUpdateRect GetTime() IsKeyPressed SetExitWithCode

32 Displayable Objects Again, know that these functions exist and roughly what they do (not the details of how they do it) Update method Set the new X and Y coordinates, regularly e.g. maintain a speed Draw method Set the (foreground) pixel colours Undraw object by copying the background Notice the useful functions available: RedrawBackground GetRedrawRect StoreLastScreenPositionAndUpdateRect

33 Next Lecture Copy constructors Assignment operators new and delete
Intro to inheritance


Download ppt "G52CFJ C/C++ for Java Programmers Lecture 13"

Similar presentations


Ads by Google