Copy Vs Assignment C# Employee Introduction To Classes And Objects

Why OOP?

Suppose that you want to assemble your own PC, you go to a hardware store and pick up a motherboard, a processor, some RAMs, a hard disk, a casing, a power supply, and put them together.  You turn on the power, and the PC runs.  You need not worry whether the motherboard is a 4-layer or 6-layer board, whether the hard disk has 4 or 6 plates; 3 inches or 5 inches in diameter, whether the RAM is made in Japan or Korea, and so on. You simply put the hardware components together and expect the machine to run.  Of course, you have to make sure that you have the correct interfaces, i.e., you pick an IDE hard disk rather than a SCSI hard disk, if your motherboard supports only IDE; you have to select RAMs with the correct speed rating, and so on.  Nevertheless, it is not difficult to set up a machine from hardware components.

Similarly, a car is assembled from parts and components, such as chassis, doors, engine, wheels, brake, and transmission. The components are reusable, e.g., a wheel can be used in many cars (of the same specifications).

Hardware, such as computers and cars, are assembled from parts, which are reusable components.

How about software?  Can you "assemble" a software application by picking a routine here, a routine there, and expect the program to run?  The answer is obviously no!  Unlike hardware, it is very difficult to "assemble" an application from software components.  Since the advent of computer 60 years ago, we have written tons and tons of programs.  However, for each new application, we have to re-invent the wheels and write the program from scratch.

Why re-invent the wheels?

Traditional Procedural-Oriented languages

Can we do this in traditional procedural-oriented programming language such as C, Fortran, Cobol, or Pascal?

Traditional procedural-oriented languages (such as C and Pascal) suffer some notable drawbacks in creating reusable software components:

  1. The programs are made up of functions. Functions are often not reusable. It is very difficult to copy a function from one program and reuse in another program because the the function is likely to reference the headers, global variables and other functions. In other words, functions are not well-encapsulated as a self-contained reusable unit.
  2. The procedural languages are not suitable of high-level abstraction for solving real life problems. For example, C programs uses constructs such as if-else, for-loop, array, function, pointer, which are low-level and hard to abstract real problems such as a Customer Relationship Management (CRM) system or a computer soccer game. (Imagine using assembly codes, which is a very low level code, to write a computer soccer game. C is better but no much better.)

In brief, the traditional procedural-languages separate the data structures and algorithms of the software entities.

Object-Oriented Programming Languages

Object-oriented programming (OOP) languages are designed to overcome these problems.

  1. The basic unit of OOP is a class, which encapsulates both the static attributes and dynamic behaviors within a "box", and specifies the public interface for using these boxes. Since the class is well-encapsulated (compared with the function), it is easier to reuse these classes. In other words, OOP combines the data structures and algorithms of a software entity inside the same box.
  2. OOP languages permit higher level of abstraction for solving real-life problems. The traditional procedural language (such as C and Pascal) forces you to think in terms of the structure of the computer (e.g. memory bits and bytes, array, decision, loop) rather than thinking in terms of the problem you are trying to solve. The OOP languages (such as Java, C++, C#) let you think in the problem space, and use software objects to represent and abstract entities of the problem space to solve the problem.

As an example, suppose you wish to write a computer soccer games (which I consider as a complex application). It is quite difficult to model the game in procedural-oriented languages. But using OOP languages, you can easily model the program accordingly to the "real things" appear in the soccer games.

  • Player: attributes include name, number, location in the field, and etc; operations include run, jump, kick-the-ball, and etc.
  • Ball:
  • Reference:
  • Field:
  • Audience:
  • Weather:

Most importantly, some of these classes (such as and ) can be reused in another application, e.g., computer basketball game, with little or no modification.

Benefits of OOP

The procedural-oriented languages focus on procedures, with function as the basic unit. You need to first figure out all the functions and then think about how to represent data.

The object-oriented languages focus on components that the user perceives, with objects as the basic unit. You figure out all the objects by putting all the data and operations that describe the user's interaction with the data.

Object-Oriented technology has many benefits:

  • Ease in software design as you could think in the problem space rather than the machine's bits and bytes. You are dealing with high-level concepts and abstractions. Ease in design leads to more productive software development.
  • Ease in software maintenance: object-oriented software are easier to understand, therefore easier to test, debug, and maintain.
  • Reusable software: you don't need to keep re-inventing the wheels and re-write the same functions for different situations. The fastest and safest way of developing a new application is to reuse existing codes - fully tested and proven codes.

OOP Basics

Classes & Instances

Class: A class is a definition of objects of the same kind. In other words, a class is a blueprint, template, or prototype that defines and describes the static attributes and dynamic behaviors common to all objects of the same kind.

Instance: An instance is a realization of a particular item of a class. In other words, an instance is an instantiation of a class. All the instances of a class have similar properties, as described in the class definition. For example, you can define a class called "" and create three instances of the class "" for "", "" and "".

The term "object" usually refers to instance. But it is often used quite loosely, which may refer to a class or an instance.

A Class is a 3-Compartment Box encapsulating Data and Functions

A class can be visualized as a three-compartment box, as illustrated:

  1. Classname (or identifier): identifies the class.
  2. Data Members or Variables (or attributes, states, fields): contains the static attributes of the class.
  3. Member Functions (or methods, behaviors, operations): contains the dynamic operations of the class.

In other words, a class encapsulates the static attributes (data) and dynamic behaviors (operations that operate on the data) in a box.

Class Members: The data members and member functions are collectively called class members.

The followings figure shows a few examples of classes:

The following figure shows two instances of the class , identified as "" and "".

Unified Modeling Language (UML) Class and Instance Diagrams: The above class diagrams are drawn according to the UML notations. A class is represented as a 3-compartment box, containing name, data members (variables), and member functions, respectively. classname is shown in bold and centralized. An instance (object) is also represented as a 3-compartment box, with instance name shown as and underlined.

Brief Summary
  1. A class is a programmer-defined, abstract, self-contained, reusable software entity that mimics a real-world thing.
  2. A class is a 3-compartment box containing the name, data members (variables) and the member functions.
  3. A class encapsulates the data structures (in data members) and algorithms (member functions). The values of the data members constitute its state. The member functions constitute its behaviors.
  4. An instance is an instantiation (or realization) of a particular item of a class.

Class Definition

In C++, we use the keyword to define a class. There are two sections in the class declaration: and , which will be explained later. For examples,

classCircle { private: double radius; string color; public: double getRadius(); double getArea(); }classSoccerPlayer { private: int number; string name; int x, y; public: void run(); void kickBall(); }

Class Naming Convention: A classname shall be a noun or a noun phrase made up of several words. All the words shall be initial-capitalized (camel-case). Use a singular noun for classname. Choose a meaningful and self-descriptive classname. For examples, , , , and .

Creating Instances of a Class

To create an instance of a class, you have to:

  1. Declare an instance identifier (name) of a particular class.
  2. Invoke a constructor to construct the instance (i.e., allocate storage for the instance and initialize the variables).

For examples, suppose that we have a class called , we can create instances of as follows:

Circle c1(1.2, "red"); Circle c2(3.4); Circle c3;

Alternatively, you can invoke the constructor explicitly using the following syntax:

Circle c1 = Circle(1.2, "red"); Circle c2 = Circle(3.4); Circle c3 = Circle();

Dot (.) Operator

To reference a member of a object (data member or member function), you must:

  1. First identify the instance you are interested in, and then
  2. Use the dot operator () to reference the member, in the form of .

For example, suppose that we have a class called , with two data members ( and ) and two functions ( and ). We have created three instances of the class , namely, , and . To invoke the function , you must first identity the instance of interest, says , then use the dot operator, in the form of , to invoke the function of instance .

For example,

Circle c1(1.2, "blue"); Circle c2(3.4, "green"); cout << c1.getArea() << endl; cout << c2.getArea() << endl; c1.radius = 5.5; c2.radius = 6.6;

Calling without identifying the instance is meaningless, as the radius is unknown (there could be many instances of - each maintaining its own radius).

In general, suppose there is a class called with a data member called and a member function called . An instance called is constructed for . You use and .

Data Members (Variables)

A data member (variable) has a name (or identifier) and a type; and holds a value of that particular type (as descried in the earlier chapter). A data member can also be an instance of a certain class (to be discussed later).

Data Member Naming Convention: A data member name shall be a noun or a noun phrase made up of several words. The first word is in lowercase and the rest of the words are initial-capitalized (camel-case), e.g., , , , and . Take note that variable name begins with an lowercase, while classname begins with an uppercase.

Member Functions

A member function (as described in the earlier chapter):

  1. receives parameters from the caller,
  2. performs the operations defined in the function body, and
  3. returns a piece of result (or void) to the caller.

Member Function Naming Convention: A function name shall be a verb, or a verb phrase made up of several words. The first word is in lowercase and the rest of the words are initial-capitalized (camel-case). For example, , .

Take note that data member name is a noun (denoting a static attribute), while function name is a verb (denoting an action). They have the same naming convention. Nevertheless, you can easily distinguish them from the context. Functions take arguments in parentheses (possibly zero argument with empty parentheses), but variables do not. In this writing, functions are denoted with a pair of parentheses, e.g., , for clarity.

Putting them Together: An OOP Example

A class called is to be defined as illustrated in the class diagram. It contains two data members: (of type ) and (of type ); and three member functions: , , and .

Three instances of s called , , and shall then be constructed with their respective data members, as shown in the instance diagrams.

In this example, we shall keep all the codes in a single source file called .

CircleAIO.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 #include <iostream> #include <string> using namespace std; class Circle { private: double radius; string color; public: Circle(double r = 1.0, string c = "red") { radius = r; color = c; } double getRadius() { return radius; } string getColor() { return color; } double getArea() { return radius*radius*3.1416; } }; int main() { Circle c1(1.2, "blue"); cout << "Radius=" << c1.getRadius() << " Area=" << c1.getArea() << " Color=" << c1.getColor() << endl; Circle c2(3.4); cout << "Radius=" << c2.getRadius() << " Area=" << c2.getArea() << " Color=" << c2.getColor() << endl; Circle c3; cout << "Radius=" << c3.getRadius() << " Area=" << c3.getArea() << " Color=" << c3.getColor() << endl; return 0; }

To compile and run the program (with GNU GCC under Windows):

> g++ -o CircleAIO.exe CircleAIO.cpp > CircleAIO Radius=1.2 Area=4.5239 Color=blue Radius=3.4 Area=36.3169 Color=red Radius=1 Area=3.1416 Color=red

Constructors

A constructor is a special function that has the function name same as the classname. In the above class, we define a constructor as follows:

Circle(double r = 1.0, string c = "red") { radius = r; color = c; }

A constructor is used to construct and initialize all the data members. To create a new instance of a class, you need to declare the name of the instance and invoke the constructor. For example,

Circle c1(1.2, "blue"); Circle c2(3.4); Circle c3;

A constructor function is different from an ordinary function in the following aspects:

  • The name of the constructor is the same as the classname.
  • Constructor has no return type (or implicitly returns ). Hence, no statement is allowed inside the constructor's body.
  • Constructor can only be invoked once to initialize the instance constructed. You cannot call the constructor afterwards in your program.
  • Constructors are not inherited (to be explained later).

Default Arguments for Functions

In C++, you can specify the default value for the trailing arguments of a function (including constructor) in the function header. For example,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include <iostream> using namespace std; int sum(int n1, int n2, int n3 = 0, int n4 = 0, int n5 = 0); int main() { cout << sum(1, 1, 1, 1, 1) << endl; cout << sum(1, 1, 1, 1) << endl; cout << sum(1, 1, 1) << endl; cout << sum(1, 1) << endl; // cout << sum(1) << endl; // error: too few arguments } int sum(int n1, int n2, int n3, int n4, int n5) { return n1 + n2 + n3 + n4 + n5; }

"public" vs. "private" Access Control Modifiers

An access control modifier can be used to control the visibility of a data member or a member function within a class. We begin with the following two access control modifiers:

  1. : The member (data or function) is accessible and available to all in the system.
  2. : The member (data or function) is accessible and available within this class only.

For example, in the above definition, the data member is declared . As the result, is accessible inside the class, but NOT outside theclass. In other words, you cannot use "" to refer to 's in . Try inserting the statement "" in and observe the error message:

CircleAIO.cpp:8:11: error: 'double Circle::radius' is private

Try moving to the section, and re-run the statement.

On the other hand, the function is declared in the class. Hence, it can be invoked in the .

UML Notation: In notation, members are denoted with a "", while members with a "" in the class diagram.

Information Hiding and Encapsulation

A class encapsulates the static attributes and the dynamic behaviors into a "3-compartment box". Once a class is defined, you can seal up the "box" and put the "box" on the shelve for others to use and reuse. Anyone can pick up the "box" and use it in their application. This cannot be done in the traditional procedural-oriented language like C, as the static attributes (or variables) are scattered over the entire program and header files. You cannot "cut" out a portion of C program, plug into another program and expect the program to run without extensive changes.

Data member of a class are typically hidden from the outside word, with access control modifier. Access to the private data members are provided via assessor functions, e.g., and .

This follows the principle of information hiding. That is, objects communicate with each others using well-defined interfaces (public functions). Objects are not allowed to know the implementation details of others. The implementation details are hidden or encapsulated within the class. Information hiding facilitates reuse of the class.

Rule of Thumb: Do not make any data member , unless you have a good reason.

Getters and Setters

To allow other to read the value of a data member says , you shall provide a get function (or getter or accessor function) called . A getter need not expose the data in raw format. It can process the data and limit the view of the data others will see. Getters shall not modify the data member.

To allow other classes to modify the value of a data member says , you shall provide a set function (or setter or mutator function) called . A setter could provide data validation (such as range checking), and transform the raw data into the internal representation.

For example, in our class, the data members and are declared . That is to say, they are only available within the class and not visible outside the class - including . You cannot access the data members and from the directly - via says or . The class provides two public accessor functions, namely, and . These functions are declared . The can invoke these public accessor functions to retrieve the and of a object, via says and .

There is no way you can change the or of a object, after it is constructed in . You cannot issue statements such as to change the of instance , as is declared as in the class and is not visible to other including.

If the designer of the class permits the change the and after a object is constructed, he has to provide the appropriate setter, e.g.,

void setColor(string c) { color = c; } void setRadius(double r) { radius = r; }

With proper implementation of information hiding, the designer of a class has full control of what the user of the class can and cannot do.

Keyword "this"

You can use keyword "" to refer to this instance inside a class definition.

One of the main usage of keyword is to resolve ambiguity between the names of data member and function parameter. For example,

class Circle { private: double radius; ...... public: void setRadius(double radius) { this->radius = radius; } ...... }

In the above codes, there are two identifiers called - a data member and the function parameter. This causes naming conflict. To resolve the naming conflict, you could name the function parameter instead of . However, is more approximate and meaningful in this context. You can use keyword to resolve this naming conflict. "" refers to the data member; while "" resolves to the function parameter.

"" is actually a pointer to this object. I will explain pointer and the meaning of "" operator later.

Alternatively, you could use a prefix (such as ) or suffix (such as ) to name the data members to avoid name crashes. For example,

class Circle { private: double m_radius; ...... public: void setRadius(double radius) { m_radius = radius; } ...... }

C++ Compiler internally names their data members beginning with a leading underscore () and local variables with 2 leading underscores (e.g., ). Hence, avoid name beginning with underscore in your program.

"const" Member Functions

A member function, identified by a keyword at the end of the member function's header, cannot modifies any data member of this object. For example,

double getRadius() const { radius = 0; // error: assignment of data-member 'Circle::radius' in read-only structure return radius; }

Convention for Getters/Setters and Constructors

The constructor, getter and setter functions for a data member called of type in a class have the following conventions:

class Aaa { private: T xxx; public: Aaa(T x) { xxx = x; } Aaa(T xxx) { this->xxx = xxx; } Aaa(T xxx) : xxx(xxx) { } T getXxx() const { return xxx; } void setXxx(T x) { xxx = x; } void setXxx(T xxx) { this->xxx = xxx; } }

For a variable , the getter shall be named , instead of , as follows:

private: bool xxx; public: bool isXxx() const { return xxx; } void setXxx(bool x) { xxx = x; } void setXxx(bool xxx) { this->xxx = xxx; }

Default Constructor

A default constructor is a constructor with no parameters, or having default values for all the parameters. For example, the above 's constructor can be served as default constructor with all the parameters default.

Circle c1; Circle c1();// Error! // (This declares c1 as a function that takes no parameter and returns a Circle instance)

If C++, if you did not provide ANY constructor, the compiler automatically provides a default constructor that does nothing. That is,

ClassName::ClassName() { }

Compiler will not provide a default constructor if you define any constructor(s). If all the constructors you defined require arguments, invoking no-argument default constructor results in error. This is to allow class designer to make it impossible to create an uninitialized instance, by NOT providing an explicit default constructor.

Constructor's Member Initializer List

Instead of initializing the private data members inside the body of the constructor, as follows:

Circle(double r = 1.0, string c = "red") { radius = r; color = c; }

We can use an alternate syntax called member initializer list as follows:

Circle(double r = 1.0, string c = "red") : radius(r), color(c) { }

Member initializer list is placed after the constructor's header, separated by a colon (). Each initializer is in the form of . For fundamental type, it is equivalent to . For object, the constructor will be invoked to construct the object. The constructor's body (empty in this case) will be run after the completion of member initializer list.

It is recommended to use member initializer list to initialize all the data members, as it is often more efficient than doing assignment inside the constructor's body.

*Destructor

A destructor, similar to constructor, is a special function that has the same name as the classname, with a prefix , e.g., . Destructor is called implicitly when an object is destroyed.

If you do not define a destructor, the compiler provides a default, which does nothing.

class MyClass { public: ~MyClass() { } ...... }
Advanced Notes
  • If your class contains data member which is dynamically allocated (via or operator), you need to free the storage via or .

*Copy Constructor

A copy constructor constructs a new object by copying an existing object of the same type. In other words, a copy constructor takes an argument, which is an object of the same class.

If you do not define a copy constructor, the compiler provides a default which copies all the data members of the given object. For example,

Circle c4(7.8, "blue"); cout << "Radius=" << c4.getRadius() << " Area=" << c4.getArea() << " Color=" << c4.getColor() << endl; Circle c5(c4); cout << "Radius=" << c5.getRadius() << " Area=" << c5.getArea() << " Color=" << c5.getColor() << endl;

The copy constructor is particularly important. When an object is passed into a function by value, the copy constructor will be used to make a clone copy of the argument.

Advanced Notes
  • Pass-by-value for object means calling the copy constructor. To avoid the overhead of creating a clone copy, it is usually better to pass-by-reference-to-, which will not have side effect on modifying the caller's object.
  • The copy constructor has the following signature: class MyClass { private: T1 member1; T2 member2; public: MyClass(const MyClass & rhs) { member1 = rhs.member1; member2 = rhs.member2; } ...... }
  • The default copy constructor performs shadow copy. It does not copy the dynamically allocated data members created via or operator.

*Copy Assignment Operator (=)

The compiler also provides a default assignment operator (), which can be used to assign one object to another object of the same class via memberwise copy. For example, using the class defined earlier,

Circle c6(5.6, "orange"), c7; cout << "Radius=" << c6.getRadius() << " Area=" << c6.getArea() << " Color=" << c6.getColor() << endl; cout << "Radius=" << c7.getRadius() << " Area=" << c7.getArea() << " Color=" << c7.getColor() << endl; c7 = c6; cout << "Radius=" << c7.getRadius() << " Area=" << c7.getArea() << " Color=" << c7.getColor() << endl;
Advanced Notes
  • You could overload the assignment opeator to override the default.
  • The copy constructor, instead of copy assignment operator, is used in declaration: Circle c8 = c6;
  • The default copy assignment operator performs shadow copy. It does not copy the dynamically allocated data members created via or operator.
  • The copy assignment operator has the following signature: class MyClass { private: T1 member1; T2 member2; public: MyClass & operator=(const MyClass & rhs) { member1 = rhs.member1; member2 = rhs.member2; return *this; } ...... }
  • The copy assignment operator differs from the copy constructor in that it must release the dynamically allocated contents of the target and prevent self assignment. The assignment operator shall return a reference of this object to allow chaining operation (such as ).
  • The default constructor, default destructor, default copy constructor, default copy assignment operators are known as special member functions, in which the compiler will automatically generate a copy if they are used in the program and not explicitly defined.

Separating Header and Implementation

For better software engineering, it is recommended that the class declaration and implementation be kept in 2 separate files: declaration is a header file ""; while implementation in a "". This is known as separating the public interface (header declaration) and the implementation. Interface is defined by the designer, implementation can be supplied by others. While the interface is fixed, different vendors can provide different implementations. Furthermore, only the header files are exposed to the users, the implementation can be provided in an object file "" (or in a library). The source code needs not given to the users.

I shall illustrate with the following examples.

Example: The Circle Class

Instead of putting all the codes in a single file. We shall "separate the interface and implementation" by placing the codes in 3 files.

  1. : defines the public interface of the class.
  2. : provides the implementation of the class.
  3. : A test driver program for the class.
Circle.h - Header
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 #include <string> using namespace std; class Circle { private: double radius; string color; public: Circle(double radius = 1.0, string color = "red"); double getRadius() const; void setRadius(double radius); string getColor() const; void setColor(string color); double getArea() const; };

Program Notes:

  • The header file contains declaration statements, that tell the compiler about the names and types, and function prototypes without the implementation details.
  • C++98/03 does NOT allow you to assign an initial value to a data member (except members). Date members are to be initialized via the constructor. For example, double radius = 1.0; // error: ISO C++ forbids in-class initialization of non-const static member 'radius' C++11 allows in-class initialization of data members.
  • You can provide default value to function's arguments in the header. For example, Circle(double radius = 1.0, string color = "red");
  • Header contains function prototype, the parameter names are ignored by the compiler, but good to serve as documentation. For example, you can leave out the parameter names in the prototype as follows: Circle(double = 1.0, string = "red");

Header files shall contains constants, function prototypes, class/struct declarations.

Circle.cpp - Implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 #include "Circle.h" Circle::Circle(double r, string c) { radius = r; color = c; } double Circle::getRadius() const { return radius; } void Circle::setRadius(double r) { radius = r; } string Circle::getColor() const { return color; } void Circle::setColor(string c) { color = c; } double Circle::getArea() const { return radius*radius*3.14159265; }

Program Notes:

  • The implementation file provides the definition of the functions, which are omitted from the declaration in the header file.
  • #include "Circle.h"
    The compiler searches the headers in double quotes (such as ) in the current directory first, then the system's include directories. For header in angle bracket (such as ), the compiler does NOT searches the current directory, but only the system's include directories. Hence, use double quotes for user-defined headers.
  • Circle::Circle(double r, string c) {
    You need to include the (called class scope resolution operator) in front of all the members names, so as to inform the compiler this member belong to a particular class.
    (Class Scope: Names defined inside a class have so-called class scope. They are visible within the class only. Hence, you can use the same name in two different classes. To use these names outside the class, the class scope resolution operator is needed.)
  • You CANNOT place the default arguments in the implementation (they shall be placed in the header). For example, Circle::Circle(double r = 1.0, string c = "red") { // error!
Compiling the Circle Class

You can compile the to an object file called , via option (compile-only) in GNU GCC:

> g++ -c Circle.cpp

To use the class, the user needs and . He does not need . In other words, you do not need to give away your source codes, but merely the public declarations and the object codes.

TestCircle.cpp - Test Driver

Let's write a test program to use the class created.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 #include <iostream> #include "Circle.h" using namespace std; int main() { Circle c1(1.2, "red"); cout << "Radius=" << c1.getRadius() << " Area=" << c1.getArea() << " Color=" << c1.getColor() << endl; c1.setRadius(2.1); c1.setColor("blue"); cout << "Radius=" << c1.getRadius() << " Area=" << c1.getArea() << " Color=" << c1.getColor() << endl; Circle c2; cout << "Radius=" << c2.getRadius() << " Area=" << c2.getArea() << " Color=" << c2.getColor() << endl; return 0; }
Compiling the Test Program

To compile with the object code (and ):

> g++ -o TestCircle.exe TestCircle.cpp Circle.o

You can also compile with the source code (and )

> g++ -o TestCircle.exe TestCircle.cpp Circle.cpp

Example: The Time Class

Let's write a class called , which models a specific instance of time with hour, minute and second values, as shown in the class diagram.

The class contains the following members:

  • Three data members: (0-23), (0-59) and (0-59), with default values of 0.
  • A constructor , which initializes the data members , and with the values provided by the caller.
  • getters and setters for private data members: , , , , , and .
  • A member function to set the values of , and given by the caller.
  • A member function to print this instance in the format "", zero-filled, e.g., .
  • A member function , which increase this instance by one second. of shall be .

Let's write the code for the class, with the header and implementation separated in two files: and .

Header - Time.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26#ifndef TIME_H#define TIME_H class Time { private: int hour; int minute; int second; public: Time(int h = 0, int m = 0, int s = 0); int getHour() const; void setHour(int h); int getMinute() const; void setMinute(int m); int getSecond() const; void setSecond(int s); void setTime(int h, int m, int s); void print() const; void nextSecond(); }; #endif
Dissecting Time.h

#ifndef TIME_H
#define TIME_H
......
#endif
To prevent an header file from included more than once into a source file (which could result in compilation error if an entity is declared twice, e.g., ), we wrap the header codes within a pair of preprocessor directives (if not define) and . The codes within the if-block will only be included if the identifier has not been defined. This is true for the first inclusion, which also defines the identifier (the first directive in body of the if-block). No subsequent inclusion is possible, since has been defined during the first inclusion. By convention, use the identifier (or ) for header .

class Time {
private:
......
public:
......
};
The header contains the class declaration for the class . It is divided into two sections: and . The members (data or functions) are accessible by members of this class only, while members are visible by all (such as the function which is outside the class). The class declaration must be terminated by a semicolon.

private:
   int hour;
   int minute;
   int second;
public:
   ......
We declare 3 private data members called , and . In C++98/C++03, you are NOT allow to initialize a data member in the class declaration (except data members). For example, setting causes a compilation error. Instead, the data members are to be initialized in the constructor (to be shown later). The newer C++11 allows initialization of data members.

Only member function prototypes are listed in the class declaration. A function prototype consists of the return-type, function name and parameter types.

Time(int h = 0, int m = 0, int s = 0);
declares the so-called constructor. A constructor is a special function that has the same name as the class. A constructor has no return type, or implicitly return . No statement is allowed inside the constructor's body. A constructor can only be used during the instance declaration to initialize the data members of the instance. It cannot be invoked thereafter.

In the function prototypes of the header, we can set the default values of the function's parameters for any function member using "". In this case, this constructor can be invoked with 0 to 3 arguments, the omitted trailing arguments will be set to their default values, e.g.,

Time t1(1, 2, 3); Time t2(1, 2); Time t3(1); Time t4;

The identifiers , and are not needed in the function prototype - you only need to specify the parameters' types. But they serve as proper documentation, and are strongly recommended.

int getHour() const;
void setHour(int h);
int getHour() const;
void setHour(int h);
int getHour() const;
void setHour(int h);
declare the so-called getter and setter for the private data member , and . Since the data members are and are not accessible outside the class, getters and setters are often provided to read and modify the data members. By convention, a getter receives nothing () from the caller and returns a value of the type of the data member; a setter receives a value of the type of the data member and returns . Setters may validate the input before setting the value of the data member.
We declare the getter functionconstant, by placing the keyword after the function parameter list. A member function cannot modify any data member of this object. Getter does not need to modify any data member.

void setTime(int h, int m, int s);
declares a public member function to set the , and of this instance in one call.

void print() const;
declares a public member function to print this instance in the format , zero-filled, e.g., . The function returns .

void nextSecond();
declares a public member function to increase this instance by one second. For example, becomes . The function returns .

Implementation - Time.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 #include <iostream> #include <iomanip> #include "Time.h" using namespace std; Time::Time(int h, int m, int s) { hour = h; minute = m; second = s; } int Time::getHour() const { return hour; } void Time::setHour(int h) { hour = h; } int Time::getMinute() const { return minute; } void Time::setMinute(int m) { minute = m; } int Time::getSecond() const { return second; } void Time::setSecond(int s) { second = s; } void Time::setTime(int h, int m, int s) { hour = h; minute = m; second = s; } void Time::print() const { cout << setfill('0'); cout << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second << endl; } void Time::nextSecond() { ++second; if (second >= 60) { second = 0; ++minute; } if (minute >= 60) { minute = 0; ++hour; } if (hour >= 24) { hour = 0; } }
Dissecting Time.cpp

The implementation file contains member's definitions (whereas the header file contains the declarations), in particular, member functions.

All member's identifiers in the implementation are preceded by the classname and the scope resolution operator (), e.g., and , so that the compiler can tell that these identifiers belong to a particular class, in this case, .

Time::Time(int h, int m, int s) {
   hour = h;
   minute = m;
   second = s;
}
In the constructor, we initialize the data members , and based on the inputs provided by the caller. C++ does NOT initialize fundamental-type (e.g., , ) data members. It also does NOT issue an error message if you use an data member before it is initialized. Hence, It is strongly recommended to initialize all the data members in the constructor, so that the constructed instance is complete, instead of relying on the user to set the values of the data members after construction.

The default values of the parameters are specified in the class declaration (in the header), NOT in the function definition. Placing a default value in function definition (e.g., ) causes a compilation error.

Take note that we have not included input validation (e.g., hour shall be between 0 and 23) in the constructor (and setters). We shall do that in the later example.

int Time::getHour() const {
   return hour;
}
the public getter for private data member simply returns the value of the data member .

void Time::setHour(int h) {
   hour = h;
}
the public setter for private data member sets the data member to the given value . Again, there is no input validation for h (shall be between 0 to 23).

The rest of the function definitions are self-explanatory.

"this" Pointer

Instead of naming the function parameters , and , we would like to name the parameters , and , which are semantically more meaningful. However, these names crashes with the names of private data members. C++ provides a keyword (which is a pointer to this instance - to be discussed later) to differentiate between the data members and function parameters. , and refer to the data members; while , , and refer to the function parameters. We can rewrite the constructor and setter as follows:

Time::Time(int hour, int minute, int second) { this->hour = hour; this->minute = minute; this->second = second; } Time::setHour(int hour) { this->hour = hour; } Time::getHour() const { return this->hour; }
Member Initializer List

C++ provide an alternative syntax to initialize data members in the constructor called member initializer list. For example,

Time::Time(int h, int m, int s) : hour(h), minute(m), second(s) { }

The member initializer list is placed after the function parameter list, separated by a colon, in the form of . For fundamental-type data members (e.g., , ), is the same as . For object data members (to be discussed later), the copy constructor will be invoked. The function body will be executed after the member initializer list, which is empty in this case.

The data members in the initializer list are initialized in the order of their declarations in the class declaration, not the order in the initializer list.

Test Driver - TestTime.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 #include <iostream> #include "Time.h" using namespace std; int main() { Time t1(23, 59, 59); t1.print(); t1.setHour(12); t1.setMinute(30); t1.setSecond(15); t1.print(); cout << "Hour is " << t1.getHour() << endl; cout << "Minute is " << t1.getMinute() << endl; cout << "Second is " << t1.getSecond() << endl; Time t2; t2.print(); t2.setTime(1, 2, 3); t2.print(); Time t3(12); t3.print(); Time t4(23, 59, 58); t4.print(); t4.nextSecond(); t4.print(); t4.nextSecond(); t4.print(); Time t5(25, 61, 99); t5.print(); }
Dissecting TestTime.cpp

The test driver tests the constructor (with and without the default values) and all the public member functions. Clearly, no input validation is carried out, as reflected in instance .

Exercise

Add member functions , , , , to the class.

Compiling the Program

You can compile all the source file together to get the executable file as follows:

> g++ -o TestTime.exe Time.cpp TestTime.cpp > TestTime

Alternatively, you can compile into an object file , and then the test driver with the object file. In this way, you only distribute the object file and header file, not the source file.

> g++ -c Time.cpp > g++ -o TestTime.exe TestTime.cpp Time.o > TestTime

Example: The Point Class

The class, as shown in the class diagram, models 2D points with x and y co-ordinates.

In the class diagram, "" denotes member; "" denotes member. "" specifies the default value of a data member.

The class contains the followings:

  • Private data members and (of type ), with default values of 0.
  • A constructor, getters and setters for private data member and .
  • A function setXY() to set both and coordinates of a .
  • A function which returns . You can use the built-in function in to compute the square root.
  • A function which returns . You can use the built-in function in to compute the gradient in radians.
  • A function which prints "" of this instance.
Point.h - Header
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 #ifndef POINT_H #define POINT_H class Point { private: int x; int y; public: Point(int x = 0, int y = 0); int getX() const; void setX(int x); int getY() const; void setY(int y); void setXY(int x, int y); double getMagnitude() const; double getArgument() const; void print() const; }; #endif
Point.cpp - Implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 #include "Point.h" #include <iostream> #include <cmath> using namespace std; Point::Point(int x, int y) : x(x), y(y) { } int Point::getX() const { return x; } void Point::setX(int x) { this->x = x; } int Point::getY() const { return y; } void Point::setY(int y) { this->y = y; } void Point::setXY(int x, int y) { this->x = x; this->y = y; } double Point::getMagnitude() const { return sqrt(x*x + y*y); } double Point::getArgument() const { return atan2(y, x); } void Point::print() const { cout << "(" << x << "," << y << ")" << endl; }
TestPoint.cpp - Test Driver
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 #include <iostream> #include <iomanip> #include "Point.h" using namespace std; int main() { Point p1(3, 4); p1.print(); cout << "x = " << p1.getX() << endl; cout << "y = " << p1.getY() << endl; cout << fixed << setprecision(2); cout << "mag = " << p1.getMagnitude() << endl; cout << "arg = " << p1.getArgument() << endl; p1.setX(6); p1.setY(8); p1.print(); p1.setXY(1, 2); p1.print(); Point p2; p2.print(); }

Example: The Account Class

A class called , which models a bank account, is designed as shown in the class diagram. It contains:

  • Two private data members: () and (), which maintains the current account balance.
  • Public functions and , which adds or subtracts the given amount from the balance, respectively. The function shall print "amount withdrawn exceeds the current balance!" if is more than .
  • A public function , which shall print "A/C no: xxx Balance=xxx" (e.g., A/C no: 991234 Balance=$88.88), with rounded to two decimal places.
Header file - Account.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #ifndef ACCOUNT_H #define ACCOUNT_H class Account { private: int accountNumber; double balance; public: Account(int accountNumber, double balance = 0.0); int getAccountNumber() const; double getBalance() const; void setBalance(double balance); void credit(double amount); void debit(double amount); void print() const; }; #endif
Implementation file - Account.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #include <iostream> #include <iomanip> #include "Account.h" using namespace std; Account::Account(int no, double b) : accountNumber(no), balance(b) { } int Account::getAccountNumber() const { return accountNumber; } double Account::getBalance() const { return balance; } void Account::setBalance(double b) { balance = b; } void Account::credit(double amount) { balance += amount; } void Account::debit(double amount) { if (amount <= balance) { balance -= amount; } else { cout << "Amount withdrawn exceeds the current balance!" << endl; } } void Account::print() const { cout << fixed << setprecision(2); cout << "A/C no: " << accountNumber << " Balance=$" << balance << endl; }
Test Driver - TestAccount.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include <iostream> #include "Account.h" using namespace std; int main() { Account a1(8111, 99.99); a1.print(); a1.credit(20); a1.debit(10); a1.print(); Account a2(8222); a2.print(); a2.setBalance(100); a2.credit(20); a2.debit(200); a2.print(); return 0; }

Example: The Ball class

A class models a moving ball, designed as shown in the class diagram, contains the following members:

  • Four data members , , and to maintain the position and speed of the ball.
  • A constructor, and public getters and setters for the private data members.
  • A function , which sets the position of the ball and to set the speed of the ball.
  • A function , which increases and by and , respectively.
  • A function , which prints "", to 2 decimal places.
Header File - Ball.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 #ifndef BALL_H #define BALL_H class Ball { private: double x, y; double xSpeed, ySpeed; public: Ball(double x = 0.0, double y = 0.0, double xSpeed = 0.0, double ySpeed = 0.0); double getX() const; void setX(double x); double getY() const; void setY(double y); double getXSpeed() const; void setXSpeed(double xSpeed); double getYSpeed() const; void setYSpeed(double ySpeed); void setXY(double x, double y); void setXYSpeed(double xSpeed, double ySpeed); void move(); void print() const; }; #endif
Implementation File - Ball.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 #include <iostream> #include <iomanip> #include "Ball.h" using namespace std; Ball::Ball(double x, double y, double xSpeed, double ySpeed) : x(x), y(y), xSpeed(xSpeed), ySpeed(ySpeed) { } double Ball::getX() const { return x; } double Ball::getY() const { return y; } void Ball::setX(double x) { this->x = x; } void Ball::setY(double y) { this->y = y; } double Ball::getXSpeed() const { return xSpeed; } double Ball::getYSpeed() const { return ySpeed; } void Ball::setXSpeed(double xSpeed) { this->xSpeed = xSpeed; } void Ball::setYSpeed(double ySpeed) { this->ySpeed = ySpeed; } void Ball::setXY(double x, double y) { this->x = x; this->y = y; } void Ball::setXYSpeed(double xSpeed, double ySpeed) { this->xSpeed = xSpeed; this->ySpeed = ySpeed; } void Ball::move() { x += xSpeed; y += ySpeed; } void Ball::print() const { cout << fixed << setprecision(2); cout << "Ball @ (" << x << ',' << y << ") with speed (" << xSpeed << ',' << ySpeed << ')' << endl; }
Test Driver - TestBall.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include <iostream> #include "Ball.h" using namespace std; int main() { Ball ball; ball.print(); ball.setXY(1.1, 2.2); ball.setXYSpeed(3.3, 4.4); ball.print(); ball.setX(5.5); ball.setY(6.6); cout << "x is " << ball.getX() << endl; cout << "y is " << ball.getY() << endl; ball.move(); ball.print(); }

Example: The Author and Book Classes (for a Bookstore)

Let's start with the Author class

Let's begin with a class called , designed as shown in the class diagram. It contains:

  • Three data members: (), (), and ( of , or for unknown).
  • A constructor to initialize the , and with the given values. There are no default values for data members.
  • Getters for , and , and setter for . There is no setter for and as we assume that these attributes cannot be changed.
  • A member function that prints "name (gender) at email", e.g., "Peter Jones (m) at peter@somewhere.com".
Header File - Author.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #ifndef AUTHOR_H #define AUTHOR_H #include <string> using namespace std; class Author { private: string name; string email; char gender; public: Author(string name, string email, char gender); string getName() const; string getEmail() const; void setEmail(string email); char getGender() const; void print() const; }; #endif
Implementation File - Author.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 #include <iostream> #include "Author.h" using namespace std; Author::Author(string name, string email, char gender) { this->name = name; setEmail(email); if (gender == 'm' || gender == 'f') { this->gender = gender; } else { cout << "Invalid gender! Set to 'u' (unknown)." << endl; this->gender = 'u'; } } string Author::getName() const { return name; } string Author::getEmail() const { return email; } void Author::setEmail(string email) { size_t atIndex = email.find('@'); if (atIndex != string::npos && atIndex != 0 && atIndex != email.length()-1) { this->email = email; } else { cout << "Invalid email! Set to empty string." << endl; this->email = ""; } } char Author::getGender() const { return gender; } void Author::print() const { cout << name << " (" << gender << ") at " << email << endl; }
Dissecting the Author.cpp

Author::Author(string name, string email, char gender) {
   this->name = name;
   setEmail(email);
In this example, we use identifier in the function's parameter, which crashes with the data member's identifier . To differentiate between the two identifiers, we use the keyword , which is a pointer to this instance. refers to the data member; while refers to the function's parameter.
No input validation is done on the parameter . On the other hand, for , we invoke setter which performs input validation.

   if (gender == 'm' || gender == 'f') {
      this->gender = gender;
   } else {
      cout << "Invalid gender! Set to 'u' (unknown)." << endl;
      this->gender = 'u';
   }
}
We validate the input for (, , or for unknown). We assign for any other inputs.

void Author::setEmail(string email) {
   size_t found = email.find('@');
   if (found != string::npos && found != 0 && found != email.length()-1) {
      this->email = email;
   } else {
      cout << "Invalid email! Set to empty string." << endl;
      this->email = "";
   }
}
To validate , we assume that there is an

Classes (C# Programming Guide)

A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable. For more information, see Static Classes and Static Class Members.

Unlike structs, classes support inheritance, a fundamental characteristic of object-oriented programming. For more information, see Inheritance.

Declaring Classes

Classes are declared by using the class keyword, as shown in the following example:

The keyword is preceded by the access level. Because public is used in this case, anyone can create objects from this class. The name of the class follows the keyword. The remainder of the definition is the class body, where the behavior and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members.

Creating Objects

Although they are sometimes used interchangeably, a class and an object are different things. A class defines a type of object, but it is not an object itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance of a class.

Objects can be created by using the new keyword followed by the name of the class that the object will be based on, like this:

When an instance of a class is created, a reference to the object is passed back to the programmer. In the previous example, is a reference to an object that is based on . This reference refers to the new object but does not contain the object data itself. In fact, you can create an object reference without creating an object at all:

We don't recommend creating object references such as this one that don't refer to an object because trying to access an object through such a reference will fail at run time. However, such a reference can be made to refer to an object, either by creating a new object, or by assigning it to an existing object, such as this:

This code creates two object references that both refer to the same object. Therefore, any changes to the object made through will be reflected in subsequent uses of . Because objects that are based on classes are referred to by reference, classes are known as reference types.

Class Inheritance

Inheritance is accomplished by using a derivation, which means a class is declared by using a base class from which it inherits data and behavior. A base class is specified by appending a colon and the name of the base class following the derived class name, like this:

When a class declares a base class, it inherits all the members of the base class except the constructors.

Unlike C++, a class in C# can only directly inherit from one base class. However, because a base class may itself inherit from another class, a class may indirectly inherit multiple base classes. Furthermore, a class can directly implement more than one interface. For more information, see Interfaces.

A class can be declared abstract. An abstract class contains abstract methods that have a signature definition but no implementation. Abstract classes cannot be instantiated. They can only be used through derived classes that implement the abstract methods. By contrast, a sealed class does not allow other classes to derive from it. For more information, see Abstract and Sealed Classes and Class Members.

Class definitions can be split between different source files. For more information, see Partial Classes and Methods.

Description

In the following example, a public class that contains a single field, a method, and a special method called a constructor is defined. For more information, see Constructors. The class is then instantiated with the keyword.

Example

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

C# Programming Guide
Object-Oriented Programming
Polymorphism
Members
Methods
Constructors
Finalizers
Objects

One thought on “Copy Vs Assignment C# Employee Introduction To Classes And Objects

Leave a Reply

Your email address will not be published. Required fields are marked *