4: Data Abstraction

1. What's an object?

In C++, an object is just a variable, and the purest definition is "a region of storage" (this is a more specific way of saying:"an object must have a unique identifier," which in the case of C++ is a unique memory address). It's a place where you can store data, and it's implied that there are also operations that cab be performed on this data.

2.Encapsulation

The ability to package data with functions allows you to create a new data type. This is often called encapsulation.

3. Object details

Do you know how big is an object? Let's see below:

#include<iostream>
using namespace std;

class A
{
private:
	int a;
public:
	bool t()
	{
		return true;
	}
};

class B
{
public:
	bool t()
	{
		return true;
	}
};

int main()
{
	cout << sizeof(A) << endl;
	cout << sizeof(B) << endl;
	return 0;
}
/*
	4
	1
 */
We can see that class A has 4 bytes which is equal size of int while class B which has no variable has 1 byte.

One of the fundamental rules of objects is that each object must have a unique address, so class with no data members will always has some minimum nonzero size.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章