Inline Functions & Code Separation
Inline Functions & Code Separation
Structures
• Keeping track of data
• C-style structure
Classes: a Deeper Look, Part 1
• Class
• The public interface
• Encapsulation
• Information hiding
• Constructor
• Destructor
• Separating interface and implementation
• Inline functions
• Default memberwise assignment
1
Structs
Chapter 22.2
2
Structs
3
Structs (Deitel, 1058–1061)
Struct
Using Structs
5
Structs
Chapter 9
7
Classes, Part 1 (Deitel, 77–110)
Class
8
Classes, Part 1 (Deitel, 77–110)
Declaring a Class
Name
class Person{
public:
Person();
int getID();
void setID( int id );
string getFirstName(); Member functions
void setFirstName( string nm ); (also called methods
string getLastName();
void setLastName( string nm ); or operations)
string toString();
private:
int ID;
string firstName; Data Members
string lastName;
};
Remember the ‘;’ ! 9
Classes, Part 1 (Deitel, 77–110)
Using a Class
Instantiate an object
Using an Object
Call the member functions
12
Classes, Part 1 (Deitel, 77–110)
Information Hiding
Encapsulation
14
Classes, Part 1 (Deitel, 77–110)
Advantages
16
Classes, Part 1 (Budd)
Message Passing
Constructor
Public member function with the same name as the class and with
no return value
Called automatically to initialize the data members whenever an
object is instantiated
Implement it in one of two ways
1. Either assign values in the constructor body
Person( int id = 0, string fn = "", string ln = "" ){
setID(id);
setFirstName(fn); Appropriate if the set function does
setLastName(ln); more than simple assignment
}
2. Or use an initializer list
Person( int id = 0, string fn = "", string ln = "" )
: ID(id), firstName(fn), lastName(ln) { }
Initializer list 18
Classes, Part 1 (Deitel, 77–110, 493–502)
Instantiating an object with
default values
When an object is instantiated, the constructor
automatically initializes the data members
19
Classes, Part 1 (Deitel, 489)
Inline Functions
20
Classes, Part 1 (Deitel, 486, 489)
Separate Implementation
string Person::toString(){
return firstName + " " + lastName; Implementation
}
21
Classes, Part 1 (Deitel, 486, 489)
Separate Files for
Interface and Implementation
In C++, this is the normal approach
• Declaration goes in the header file (Person.h) – this part is
considered the “interface”
• Definition goes in the source file (Person.cpp) – this part is
considered the “implementation”
main.cpp Person.h Person.cpp
#include "Person.h" #include <string> #include "Person.h"
using std::string; string Person::getName()
int main(){ class Person{ {
Person james; public: return name;
void setName(string);
james.setName("James"); }
string getName();
} private: void Person::setName(string nm)
string name; {
}; name = nm;
}
Advantages
• Smaller header files – header files are included with the source
file
• Developer can hide the implementation details 22