CPP05 Classes and Objects

What is an Object?

Object Oriented Programming is a programming style that is intended to make thinking about programming closer to thinking about the real world.

In programming, objects are independent units, and each has its own identity, just as objects in the real world do.

An apple is an object; so is a mug. Each has its unique identity. It’s possible to have two mugs that look identical, but they are still separate, unique objects.

Objects

An object might contain other objects but they’re still different objects.

Objects also have characteristics that are used to describe them. For example, a car can be red or blue, a mug can be full or empty, and so on. These characteristics are also called attributes. An attribute describes the current state of an object.
Objects can have multiple attributes (the mug can be empty, red and large).

  • An object’s state is independent of its type; a cup might be full of water, another might be empty.

In the real world, each object behaves in its own way. The car moves, the phone rings, and so on.
The same applies to objects - behavior is specific to the object’s type.

  • So, the following three dimensions describe any object in object oriented programming: identity, attributes, behavior.
  • In programming, an object is self-contained, with its own identity. It is separate from other objects.
  • Each object has its own attributes, which describe its current state. Each exhibits its own behavior, which demonstrates what they can do.
    在这里插入图片描述

In computing, objects aren’t always representative of physical items.
For example, a programming object can represent a date, a time, a bank account. A bank account is not tangible; you can’t see it or touch it, but it’s still a well-defined object - it has its own identity, attributes, and behavior.

  • Tap Continue to dive right into Object Oriented Programming (OOP) with C++!

What is a Class?

Obejects are created using classes, which are actually the facal point of OOP.
The class describes what the object will be, but is seperate from the object itself.
In other words, a class can be describd as an object’s blueprint, description, or definition. You can use the same calss as a bluprint for creating multiple different objects. For example, in preparation to creating a new building, the architect creats a blueprint, which is used as a basis for actually building the structure. That same blueprint can be used to create multiple buildings.

Programming works in the same fashion. We first define a class, which becomes the blueprint for creating objects.

Each class has a name, and describes attributes and behavior.

In programming, the term type is used to refer to class name: We’re creating an object of a particular type.

Attributes are also referred to as properties or data.

Methods

Method is another term for a class’ behavior. A method is basically a function that belongs to a class.

Methods are similar to functions - they are blocks of code that are called, and they can also perform actions and return values.

A Class Example

For example, if we are creating a banking program, we can give our class the following characteristics:
name: BankAccount
attributes: accountNumber, balance, dateOpened
behavior: open(), close(), deposit()
The class specifies that each object should have the defined attributes and behavior. However, it doesn’t specify what the actual data is; it only provides a definition.
Once we’ve written the class, we can move on to create objects that are based on that class.
Each object is called an instance of a class. The process of creating objects is called instantiation.

Each object has its own identity, data, and behavior.

Example of a Class

Declaring a Class

Beign your class definition with the keyword class. Follow the keyword with the class name and the calss body, enclosed in a set of curly braces.
The following code declares a class called BankAccount:

class BankAccount{

};
  • A class definition must be followed by a semicolon.

Define all attributes and behavior (or members) in the body of the class, within curly braces.
You can also define an access specifier for members of the class.
A member that has been defined using the public keyword can be accessed from outside the class, as long as it’s anywhere within the scope of the class object.

  • You can also designate a class’ members as private or protected. This will be discussed in greater detail later in the course.

Let’s create a class with one public method, and have it print out “Hi”.

class BankAccount {
public:
	void sayHi() {
		cout << "Hi" << endl;
	}
};

The next step is to instantiate an object of BankAccount class, in the same way we define variable of a type, the difference being that put object’s type will be BankAccount.

int main(){
	BankAccount test;
	test.sayHi();

	system("PAUSE");
	return 0;
}

Our object named test has all the members of the class defined.
Notice the dot separator (.) that is used to access and call the method of the object.

  • We must declare a class before using it , as we do with functions.

Abstraction

Data abstraction is the concept of providing only essential information to the outside world. It’s a process of representing essential features without including implementation details.

A good real-world example is a book: When you hear the term book, you don’t know the exact specifics, i.e.: the page count, the color, the size, but you understand the idea of a book - the abstraction of the book.

  • The concept of abstraction is that we focus on essential qualities, rather than the spcific characteristics of one particular example.

Abstraction means, that we can have an idea or a concept that is completely separate from any specific instance.
It is one of the fundamental building blocks of object oriented programming.

For example, when you use cout, you’re actually using the cout object of the class ostream. This streams data to result in standard output.
cpp cout<<"Hello!"<<endl;

  • In this example, there is no need to understand how cout will display the text on the user’s screen. The only thing you need to know to be able to use it is the public interface.

Abstraction allows us to write a single bank account class, and then create different objects based on the class, for individual bank accounts, rather than creating a separate class for each bank account.
在这里插入图片描述

  • Abstraction acts as a foundation for the other object orientation fundamentals, such as inheritance and polymorphism. These will be discussed later in the course.

Encapsulation

Part of the meaning of the word encapsulation is the idea of “surrounding” an entity, not just to keep what’s inside together, but also to protect it.
In object orientation, encapsulation means more than simply combining attributes and behavior together within a class; it also means restricting access to the inner workings of that class.

The key principle here is that an object only reveals what the other application components require to effectively run the application. All else is kept out of view.

  • This is called data hiding.

For example, if we take our BankAccount class, we do not want some other part of our program to reach in and change the balance of any object, without going through the deposit() or withdraw() behaviors.
We should hide that attribute, control access to it, so it is accessible only by the object itself.
This way, the balance cannot be directly changed from outside of the object and is accessible only using its methods.
This is also known as “black boxing”, which refers to closing the inner working zones of the object, except of the pieces that we want to make public.
This allows us to change attributes and implementation of methods without altering the overall program. For example, we can come back later and change the data type of the balance attribute.

  • In summary the benefits of encapsulation are:
    - Control the way daya is accessed or modified.
    - Code is more flexible and eassy to change with new requirement.
    - Change one part of code without affecting othe part of code.

Example of Encapsulation

  • Access specifiers are used to set access levels to particular members of the class.
    The three levels of access specifiers are public, protected, and private.
    A public member is accessible from outside the class, and anywhere within the scope of the class object.

Public

For example:

#include<iostream>
#include<string>
#include<cstdlib> // used for rand()
#include<stdlib.h> // used for pause
using namespace std;

class myClass{
public:
	string name;
};

int main(){
	myClass myObj;
	myObj.name = "SoloLearn";
	cout << myObj.name << endl;

	system("PAUSE");
	return 0;
}
// Outputs "SoloLearn"

The name attribute is public; it can be accessed and modified from outside the code.

  • Access modifiers only need to be declared once; multiple members can follow a single access modifier.
  • Notice the colon (? that follows the public keyword.

Private

A private member cannot be accessed, or even viewed, from outside the class; it can be accessed only from within the class.
A public member function may be used to access the private members. For example:

#include <iostream>
#include <string>
#include<cstdlib>
using namespace std;

class myClass {
public:
	void setName(string x) {
		name = x;
	}
	string getName(){
		return name;
	}
private:
	string name;
};

int main() {
	myClass myObj;
	myObj.setName("John");
	cout<< myObj.getName()<<endl;
	
	system("PAUSE");
	return 0;
}

The name attribute is private and not accessible from the outside.
The public setName() method is used to set the name attribute.

  • If no access specifier is defined, all members of a class are set to private by default.

Access Specifiers

  • The getName() method returns the value of the private name attribute.
  • We used encapsulation to hide the name attribute from the outside code. Then we provided access to it using public methods. Our class data can be read and modified only through those methods.
  • This allows for changes to the implementation of the methods and attributes, without affecting the outside code.

Constructors

Class constructors are special memebr functions of a class. They are executed whenever new objects are created within that class.
The constructor’s name is identical to that of the calss. It has no return type, not even void.

#include<iostream>;
#include<string>;
#include<cstdlib>;
using namespace std;
// Constructors
class myClass{
public:
   myClass(){
   	cout << "Hey" << endl;
   }
   void setName(string x){
   	name = x;
   }
   string getName(){
   	return name;
   }
private:
   string name;
};

int main(){
   myClass myObj;

   system("PAUSE");
   return 0;
}
// Outputs "Hey"
  • Now, upon the creation of an object of type myClass, the constructor is automatically called.

Constructors can be very useful for setting initial values for certain member variables.
A default constructor has no parameters. However, when needed, parameters can be added to a constructor. This makes it possible to assign an initial value to an object when it’s created, as shown in the following example:

class myClass {
  public:
    myClass(string nm) {
      setName(nm);
    }
    void setName(string x) {
      name = x;
    }
    string getName() {
      return name;
    }
  private:
    string name;
};

We defined a constructor, that takes one parameter and assigns it to the name attribute using the setName() method.

When creating an object , you now need to pass the constructor’s parameter, as you would when calling a function:

#include<iostream>;
#include<string>;
#include<cstdlib>;
using namespace std;
// Constructors
class myClass{
public:
	myClass(string nm){
		setName(nm);
	}
	void setName(string x){
		name = x;
	}
	string getName(){
		return name;
	}
private:
	string name;
};

int main(){
	myClass ob1("David");
	myClass ob2("Amy");
	cout << ob1.getName()<<endl;
	cout << ob2.getName() << endl;

	system("PAUSE");
	return 0;
}
//Outputs "David"
//Outputs "Amy"

We’ve defiend two objects, and used the constructor to pass the initial value for the name attribute for each object.

It’s possible to have multiple constructors that take different numbers of parameters.

Module 5 Quiz

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值