OOP C2 Class

Reference

ref Introduction to Programming with C++ Page 250-259.

Reference is a new way to manipulate objects in C++.

A reference variable: An alias for another variable, The original data stored in the variable can be accessed and modified through its reference variable.

Declaration

Place the ampersand & in front of the variable or after the data type for the variable.

1
2
3
4
5
6
7
char c,d;        // a character
char *p;
p = &c; // a pointer to a character
char &r = c; // a reference to a character
//r and c now refer to the same variable
p = &d; //OK
r = d; //err
  • Local or global variables:type& refname = name;

    For ordinary variables, the initial value is required.

  • In parameter lists and member variables: type& refname

    Binding defined by caller or constructor.

    1
    2
    3
    void f(int& x);
    f(y); //initialized when f is called
    f(y + 2); //warn or err: y + 2 is not a virable,thus the f to recive is missing
    1. Parameters can be passed by reference thus changes made to the parameters inside the function also made to the arguments.
    2. When passing an argument by value, the argument can be a literal, a variable, an expression, or even the
      return value of another function; however, the argument must be a variable when it comes to reference.
    3. Pass-by-reference is more efficient than pass-by-value because for some object types objects a lot of memory are taken.

    A constant reference parameter could be specified to prevent its value from being changed by accident.

    1
    2
    const char &cr = c; //cannot modify cr,but can modify c
    void func(const int& a);

Pointers vs. References

Pointers Reference
can’t be null, initialized when declare can be set to null and intialized without initialized value.
an alias for an variable, dependent on an existing variable independent of existing objects
can’t change to a new “address” location can change to point to a different address

Restriction

  • No references to references
  • No pointers to references, but Reference to pointer is ok
  • No arrays of references

Class

ref Introduction to Programming with C++ Page 362-.

A class defines the properties and behaviors for objects.

example: Point

In C,

1
2
3
4
5
6
7
8
9
10
11
12
typedef struct point { float x; float y;
} Point;
Point a;
a.x = 1;a.y = 2;

void print(const Point* p) {
printf("%d %d\n",p->x,p->y);
}
void move(Point* p,int dx, int dy) {
p->x += dx; p->y += dy;
}
print(&a);

And the prototypes are

1
2
3
4
5
6
typedef struct point { 
float x;
float y;
} Point;
void print(const Point* p);
void move(Point* p,int dx, int dy);

In C++, declarations are allowed and no more typedef need for class.

1
2
3
4
5
6
7
8
9
class Point { 
public:
void init(int x,int y); //prototypes of funcs
void move(int dx,int dy);
void print() const;
private:
int x;
int y;
};

And the definitions of the functions of Point are

1
2
3
4
5
6
7
8
9
void Point::init(int ix, int iy) { 
x = ix; y = iy;
}
void Point::move(int dx,int dy) {
x+= dx; y+= dy;
}
void Point::print() const {
cout << x << ' ' << y << endl;
}

where :: is the resolver(域解析器).

  • <Class Name>::<function name> for <Class Name>

  • ::<function name> for global.

1
2
3
4
5
void S::f() { 
::f(); // Would be recursive otherwise!
::a++; // Select the global a
a--; // The a at class scope, different from above a
}

Declaration and Definition

  • The class declaration, along with the prototype of the member functions should be put into a header file.
  • The definition of the member functions should be put into another source file.

UML Diagram

Member functions

Constructors

Constructors, designed to perform initializing action, are invoked when a new object is created.

The compiler automatically(guaranteed) calls that constructor at the point an object is created if a class has a constructor, before client programmers can make operations.

peculiarities:

  1. Constructors must have the same name as the class itself.
  2. Constructors do not have a return type—not even void.
  3. Constructors,play the role of initializing objects, are invoked when an object is created.
  1. It is a common mistake to put the void keyword in front of a constructor.
  2. A (local or global) variable can be declared and initialized in one statement. However as a class member, a data field cannot be initialized when it is declared before C++ 11 standard.
1
2
3
4
5
6
7
8
9
10
11
class X{
int i;
//int i = 11; New property in C++11
public:
X(int a){
this -> i = a;
}
}

X new1 = 5; //Call a constructor requiring an integer as paramater rather than assigning 5 to new1
X new2(5); //same as above
Default constructor

A default constructor: one that can be called with no arguments.

There may be no default constructors.

1
2
3
4
5
6
7
8
9
10
struct Y {
float f;
int i;
Y(int a); //NOt a default constructor
};
Y y0[3] = {1,2,3}; //OK
Y y1[] = { Y(1), Y(2), Y(3) }; //OK
Y y2[3] = { Y(1),Y(2) }; //Too few
Y y3[7]; //Too few
Y y4; //No paramater
  • The compiler ensures that construction always happens.
  • The compiler will automatically create one for you if and only if there are no constructors for a class / struct.

Destructor

The destructor is called automatically by the compiler when the object goes out of scope.

The only evidence for a destructor call is the closing brace of the scope that surrounds the object.

The destructor is named after the name of the class with a leading tilde (~).The destructor never has any arguments.

Call a function

1
2
Point p; 
p.move(10,10);

There is a relationship with the function be called and the variable to call it.

The function itself knows it is doing something with the variable. But how? By this.

Keyword this

ref Introduction to Programming with C++ Page 455.

this:

  • a hidden parameter for all member functions, with the type of the class;
  • a natural local variable of all structs member functions that you can not define, but can use it directly;
  • a built-in pointer to calling object itself.
1
void Point::move(int dx, int dy);

can be recognized as

1
void Point::initialize(Point *this, int dx, int dy);

Inside member functions, this can be used as the pointer to the variable that calls the function.

Must specify a variable to call the function.

Object

An object represents an entity in the real world that can be distinctly identified. An object has a unique identity, state, and behavior.

An object is an instance of a class.

  • State/Properties/Attributes/Data: the properties or status, represented by data fields with their current values.
  • Behavior/Services/Operations: the functions, and to invoke a function on an object is to ask the object to perform an action.

An Objects is just a variable, and the purest definition is “a region of storage”. The struct variables learned before are just objects in C++.

Obeject-oriented thinking

Characteristics

  1. Everything is an object.
  2. program is a bunch of objects telling each other what to do by sending messages.
  3. Each object has its own memory made up of other objects.
  4. Every object has a type.
  5. All objects of a particular type can receive the same messages.

OOP C2 Class
http://example.com/2023/03/14/OOP-2/
Author
Tekhne Chen
Posted on
March 14, 2023
Licensed under