Introduction to C++: Classes and Objects, Structures and Classes, Unions and Classes
1. Introduction to C++
C++ is a general-purpose, compiled programming language developed by Bjarne Stroustrup at Bell Labs. It was originally developed as an extension of the C programming language with support for object-oriented programming features.
C++ supports multiple programming paradigms, including:
Procedural programming
Object-oriented programming
Generic programming
Functional programming features
For object-oriented programming, C++ provides important concepts such as classes, objects, encapsulation, inheritance, polymorphism, abstraction, constructors and destructors.
The fundamental difference between procedural and object-oriented programming is that procedural programming primarily organizes a program around functions and procedures, whereas object-oriented programming organizes the program around objects that combine data and behaviour.
2. Classes and Objects
Classes and objects are the fundamental building blocks of object-oriented programming in C++.
A class defines the structure and behaviour of a particular type of object, whereas an object is an instance of that class.
For example, if Student is a class, then s1, s2, and s3 can be objects of the Student class.
Class
Student
|
---------------------
| | |
s1 s2 s3
Object Object ObjectA class can contain:
Data members
Member functions
Constructors
Destructors
Access specifiers
Other nested declarations
2.1 Class
A class is a user-defined data type that combines related data and functions into a single unit.
Definition
A class is a user-defined data type that encapsulates data members and member functions and provides a blueprint for creating objects.
Syntax
class ClassName
{
private:
// data members
public:
// member functions
};For example:
class Student
{
private:
int rollNo;
float marks;
public:
void display()
{
cout << rollNo << " " << marks;
}
};Here, Student is a class.
3. Object
An object is an instance of a class.
Once a class has been defined, objects can be created using the class name.
Syntax
ClassName objectName;Example:
Student s1;Here, s1 is an object of the Student class.
Multiple objects can be created:
Student s1, s2, s3;Each object has its own state represented by its non-static data members.
4. Example of Class and Object
#include <iostream>
using namespace std;
class Student
{
public:
int rollNo;
float marks;
void display()
{
cout << "Roll Number: " << rollNo << endl;
cout << "Marks: " << marks << endl;
}
};
int main()
{
Student s1;
s1.rollNo = 101;
s1.marks = 85.5;
s1.display();
return 0;
}Output
Roll Number: 101
Marks: 85.5Explanation
The statement:
class Studentdefines the class.
The statement:
Student s1;creates an object named s1.
The members are accessed using the dot (.) operator:
s1.rollNo = 101;
s1.marks = 85.5;
s1.display();Thus, an object provides access to the accessible members of its class.
5. Class and Object: Important Relationship
A class can be considered a blueprint or logical definition, while an object represents an actual instance created from that definition.
For example:
| Class | Objects |
|---|---|
Student | s1, s2, s3 |
Car | car1, car2 |
Employee | e1, e2 |
BankAccount | account1, account2 |
A single class can therefore be used to create multiple objects.
6. Structures and Classes
C++ provides both structures (struct) and classes (class) for creating user-defined data types.
Both can contain:
Data members
Member functions
Constructors
Destructors
Access specifiers
Static members
Nested types
Inheritance and other class-related features
Therefore, a C++ structure is considerably more powerful than the traditional C structure.
However, there is an important default-access difference between a struct and a class.
7. Structure in C++
A structure is declared using the struct keyword.
Syntax
struct StructureName
{
data_members;
member_functions;
};Example:
struct Student
{
int rollNo;
float marks;
void display()
{
cout << rollNo << " " << marks;
}
};An object can be created as:
Student s1;The public data members can be accessed directly:
s1.rollNo = 101;
s1.marks = 85.5;8. Structure Example
#include <iostream>
using namespace std;
struct Student
{
int rollNo;
float marks;
void display()
{
cout << "Roll Number: " << rollNo << endl;
cout << "Marks: " << marks << endl;
}
};
int main()
{
Student s;
s.rollNo = 101;
s.marks = 88.5;
s.display();
return 0;
}Output
Roll Number: 101
Marks: 88.5This demonstrates that a C++ struct can contain both data and functions.
9. Structure vs Class
The syntax of struct and class is very similar in C++.
The most important difference is their default member access.
| Feature | struct | class |
|---|---|---|
| Keyword | struct | class |
| Default member access | public | private |
| Default base-class access | public | private |
| Member functions | Supported | Supported |
| Constructors | Supported | Supported |
| Destructors | Supported | Supported |
| Inheritance | Supported | Supported |
| Polymorphism | Supported | Supported |
| Encapsulation | Supported | Supported |
For example:
struct A
{
int x;
};Here x is public by default.
Therefore:
A obj;
obj.x = 10;is valid.
Now consider:
class B
{
int x;
};Here x is private by default.
Therefore:
B obj;
obj.x = 10; // Error10. Structure and Class Example
The following program demonstrates the difference:
#include <iostream>
using namespace std;
struct StudentStruct
{
int rollNo;
};
class StudentClass
{
int rollNo;
};
int main()
{
StudentStruct s1;
s1.rollNo = 101; // Valid
StudentClass s2;
// s2.rollNo = 102; // Error: private member
cout << s1.rollNo;
return 0;
}The important point is not that a structure cannot provide encapsulation. In C++, it can. The distinction is mainly that its members are public by default, whereas class members are private by default.
11. When to Use Structure and Class?
In C++, the choice is generally a matter of design intent and convention, not capability alone.
A struct is often used when the type primarily represents a simple collection of related values and public access is appropriate.
Example:
struct Point
{
int x;
int y;
};A class is generally preferred when the type represents an abstraction with controlled access to its internal state and associated behaviour.
Example:
class BankAccount
{
private:
double balance;
public:
void deposit(double amount);
void withdraw(double amount);
};Thus, class is commonly associated with encapsulation and abstraction, while struct is often used for simple data-oriented types.
12. Unions in C++
A union is a user-defined type in which all non-static data members share the same memory location.
Unlike a structure or class, where separate non-static data members generally have distinct storage, the members of a union overlap in storage.
Syntax
union UnionName
{
data_member1;
data_member2;
data_member3;
};Example:
union Data
{
int i;
float f;
char ch;
};Here, i, f, and ch share the same storage.
13. Memory Concept of a Union
Consider:
union Data
{
int i;
float f;
char ch;
};Conceptually:
Same Memory Location
┌─────────────────────┐
│ │
│ i / f │
│ / │
│ ch │
│ │
└─────────────────────┘Only one member's stored value should generally be treated as the active member at a time, subject to the language rules.
The size of a union is sufficient to accommodate its largest member, with alignment requirements taken into account.
14. Union Example
#include <iostream>
using namespace std;
union Data
{
int i;
float f;
};
int main()
{
Data d;
d.i = 10;
cout << "Integer: " << d.i << endl;
d.f = 25.5;
cout << "Float: " << d.f << endl;
return 0;
}Output
Integer: 10
Float: 25.5When d.f is assigned after d.i, the storage is reused for the float. The previous int value should not be treated as simultaneously preserved as an independent value.
15. Union and Class
Like a class, a union in C++ can contain:
Data members
Member functions
Constructors
Destructors
Static members
Access specifiers
For example:
union Data
{
private:
int value;
public:
void setValue(int v)
{
value = v;
}
void display()
{
cout << value;
}
};Thus, a C++ union is not limited to the simple data-only structure commonly associated with unions in C.
16. Union vs Class
The important distinction is how their non-static data members are stored.
| Feature | Union | Class |
|---|---|---|
| Keyword | union | class |
| Data members | Share storage | Normally have separate storage |
| Simultaneous independent values | Generally not for overlapping members | Yes |
| Default access | public | private |
| Member functions | Supported | Supported |
| Constructors | Supported | Supported |
| Destructors | Supported | Supported |
| Inheritance | Not supported | Supported |
| Primary purpose | Memory-efficient alternative representation | Encapsulation and object-oriented design |
17. Structure vs Union
The difference between a structure and a union is particularly important for understanding memory.
Consider:
struct Data
{
int i;
float f;
};and:
union Data
{
int i;
float f;
};In the structure, both members have their own storage.
Conceptually:
Structure
┌──────────────┐
│ i │
├──────────────┤
│ f │
└──────────────┘In the union, the members overlap:
Union
┌──────────────┐
│ i / f │
└──────────────┘Therefore, structures are suitable when all member values need to coexist, whereas unions are useful when different representations share storage and only one active representation is required at a time.
18. Structures, Unions and Classes in C++
The three constructs can be compared as follows:
| Feature | Structure | Union | Class |
|---|---|---|---|
| Keyword | struct | union | class |
| Default access | Public | Public | Private |
| Data members | Separate storage | Shared storage | Separate storage |
| Member functions | Yes | Yes | Yes |
| Constructors | Yes | Yes, subject to union restrictions | Yes |
| Destructors | Yes | Yes, subject to union restrictions | Yes |
| Inheritance | Yes | No | Yes |
| Polymorphism | Yes | No inheritance-based polymorphism | Yes |
| Encapsulation | Supported | Supported | Strongly supported by default |
| Typical use | Data-oriented types | Alternative representations/shared storage | OOP abstractions |
19. Important Concept: struct and class Are More Similar in C++ Than in C
Students coming from C often assume:
Structure = data only
Class = data + functions
This is not correct for C++.
In C++, a struct can have member functions, constructors, destructors, access specifiers and inheritance.
For example:
struct Rectangle
{
private:
int length;
int breadth;
public:
Rectangle(int l, int b)
{
length = l;
breadth = b;
}
int area()
{
return length * breadth;
}
};This is a valid C++ structure with private data, a constructor and a member function.
Therefore, the major language-level difference between struct and class is primarily their default access and default inheritance access, not simply whether they can contain functions.
20. Practical Example Combining Class, Structure and Union
The following example demonstrates the three concepts:
#include <iostream>
using namespace std;
struct Point
{
int x;
int y;
};
union Value
{
int integerValue;
float decimalValue;
};
class Rectangle
{
private:
int length;
int breadth;
public:
void setData(int l, int b)
{
length = l;
breadth = b;
}
int area()
{
return length * breadth;
}
};
int main()
{
Point p;
p.x = 10;
p.y = 20;
Value v;
v.integerValue = 100;
Rectangle r;
r.setData(10, 5);
cout << "Point: (" << p.x << ", " << p.y << ")" << endl;
cout << "Union value: " << v.integerValue << endl;
cout << "Rectangle area: " << r.area() << endl;
return 0;
}Output
Point: (10, 20)
Union value: 100
Rectangle area: 50This example demonstrates three different design purposes:
Pointuses a structure for a simple collection of related values.Valueuses a union where alternative values share storage.Rectangleuses a class to encapsulate data and behaviour.
21. Key Points to Remember
C++ supports both procedural and object-oriented programming.
A class is a user-defined type that combines data and behaviour.
An object is an instance of a class.
The dot (
.) operator is generally used to access accessible members through an object.A C++
structcan contain both data members and member functions.The default access level of a
structis public.The default access level of a
classis private.A union stores its non-static data members in overlapping storage.
A union is useful when different representations need to use the same storage.
C++ unions can contain member functions and other class-like features, but they do not support inheritance.
A class is generally preferred when designing an abstraction requiring controlled access to its internal state.
structandclassin C++ are much more similar than their C counterparts.The major default-access distinction is:
struct → public
class → private
The main memory distinction is:
structure/class → members generally have separate storage
union → members share storage
Quick Revision
C++
|
├── Class
│ ├── Data Members
│ ├── Member Functions
│ └── Objects
│
├── Structure
│ ├── Data Members
│ ├── Member Functions
│ └── Public by default
│
└── Union
├── Shared Storage
├── Data Members
├── Member Functions
└── Public by defaultThe most important distinction for examination purposes is:
Class and structure differ mainly in their default access control, whereas a union differs fundamentally because its non-static data members share the same storage.
No comments:
Post a Comment