KEMBAR78
Basic Elements of C++ | PDF | Class (Computer Programming) | C++
0% found this document useful (0 votes)
22 views15 pages

Basic Elements of C++

The document provides an overview of the basic structure of C++ programming, including classes, objects, data members, member functions, and access specifiers. It explains the concepts of static members, constructors, destructors, and their usage with examples. Additionally, it highlights the importance of encapsulation and data hiding in object-oriented programming.

Uploaded by

Priya Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views15 pages

Basic Elements of C++

The document provides an overview of the basic structure of C++ programming, including classes, objects, data members, member functions, and access specifiers. It explains the concepts of static members, constructors, destructors, and their usage with examples. Additionally, it highlights the importance of encapsulation and data hiding in object-oriented programming.

Uploaded by

Priya Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

BASIC STRUCTURE OF C++

EXAMPLE:
#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
return 0;
}
BASIC ELEMENTS OF C++:

Classes:

A class is a user-defined data type, which holds its own data members and
member functions that can be accessed and used by creating an instance of
that class.

A C++ class is like a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with
different names and brands but all of them will share some common
properties like all of them will have 4 wheels, Speed Limit, Mileage
range, etc.

Create a Class

A class must be defined before its use. C++ class is defined using the
keyword class keyword as shown:

class className {
access_specifier:

// data member

// member method
};

where,
 Data Members: These are the variables that are defined inside the class.
 Member Functions: Functions declared inside a class. Also referred to
as a member method.

Objects

When a class is defined, only the specification (attributes and behaviour) for
the object is defined.

No memory is allocated to the class definition.


To use the data and access functions defined in the class, we need to create
its objects.

Objects are the actual entities that are created as an instance of a class.

There can be as many objects of a class as desired.

If we create an actual car based on the properties of the Car class, the car
we made is the object of that class.

Create Object
Once the class is defined, we can create its object in the same way we
declare the variables of any other inbuilt data type.

className objectName;

This statement creates an object of className class.

Data members and Member functions in C+


+
"Data Member" and "Member Functions" are the new names/terms
for the members of a class, which are introduced in C++ programming
language.

The variables which are declared in any class by using


any fundamental data types (like int, char, float etc) or derived data
type (like class, structure, pointer etc.) are known as Data Members.

And the functions which are declared either in private section of public
section are known as Member functions.

Types of Data members and Member functions


in C++
There are two types of data members/member functions in C++:

1. Private members
2. Public members
1) Private members
The members which are declared in private section of the class (using
private access modifier) are known as private members.

Private members can also be accessible within the same class in which
they are declared.

2) Public members
The members which are declared in public section of the class (using
public access modifier) are known as public members.

Public members can access within the class and outside of the class by
using the object name of the class in which they are declared.

Syntax of Data members and Member functions


Consider the below syntax with real data members and members
functions in a C++ class:

class Test {
private:
int a;
float b;
char *name;

void getA() { a = 10; }


...;

public:
int count;
void getB() { b = 20; }

...;
};

Here, a, b, and name are the private data members and count is a public
data member. While, getA() is a private member function
and getB() is public member functions.
Example of Data members and Member
functions
C++ program that will demonstrate, how to declare, define and
access data members an member functions in a class?

#include <string.h>

#include <iostream>
using namespace std;

#define MAX_CHAR 30

// class definition
class person {
// private data members
private:
char name[MAX_CHAR];
int age;

// public member functions


public:
// function to get name and age
void get(char n[], int a) {
strcpy(name, n);
age = a;
}

// function to print name and age


void put() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};

// main function
int main() {
// creating an object of person class
person PER;

// calling member functions


PER.get("Alvin", 27);
PER.put();

return 0;
}

Output
Name: Alvin
Age: 27

Access Specifiers In C++:


In C++, access specifiers are keywords used to define the accessibility and visibility of
class members (data members and member functions) from outside the class. They
determine how the members of a class can be accessed by other parts of the program.
C++ provides three access specifiers:
1. Public:
 Members declared as public are accessible from anywhere in the program, both
inside and outside the class.
 Public members can be accessed directly using the dot (.) operator with an object
of the class.
 Public members define the interface of the class and are used to provide access to
the class's functionality to other parts of the program.
2. Private:
 Members declared as private are only accessible within the same class.
 Private members cannot be accessed from outside the class, neither by other
classes nor by functions that are not members of the class.
 Private members are used to encapsulate the internal state and implementation
details of a class, hiding them from external access.
 By convention, data members are usually declared as private to ensure data
encapsulation and prevent unauthorized access or modification.
3. Protected:
 Members declared as protected are accessible within the same class and its
derived classes (subclasses).
 Protected members cannot be accessed from outside the class hierarchy.
 Protected members are used when you want to allow derived classes to access
certain members of the base class while still restricting access from other parts of
the program.
 Protected members provide a level of encapsulation between public and private,
allowing inheritance and extending the functionality of a class.
For example:

class MyClass {
public:
void publicFunction() {
// Accessible from anywhere
}
private:
int privateVariable;
void privateFunction() {
// Accessible only within the class
}
protected:
void protectedFunction() {
// Accessible within the class and its derived classes
}
};
In this example:
 `publicFunction()` is a public member function that can be accessed from anywhere
in the program using an object of `MyClass`.
 `privateVariable` and `privateFunction()` are private members that can only be
accessed within the `MyClass` itself.
 `protectedFunction()` is a protected member function that can be accessed within
`MyClass` and its derived classes.
Note: Access specifiers play a crucial role in encapsulation and controlling the
accessibility of class members. They help in achieving data hiding, preventing
unauthorized access, and providing a clear interface for interacting with objects of a
class.
Syntax of Access Specifiers in C++
In C++, access specifiers are used within class definitions to control the visibility and
accessibility of class members. The three primary access specifiers are public, private,
and protected. Their syntax is

class ClassName {
public:
// Members declared here are accessible from anywhere
int publicVar;
void publicMethod();

private:
// Members declared here are accessible only within the class
int privateVar;
void privateMethod();
protected:
// Members declared here are accessible within the class and by derived classes
int protectedVar;
void protectedMethod();
};

Example of Access Specifiers in C++


Let's look at a practical example to illustrate how these access specifiers work:
 C++
#include <iostream>
using namespace std;

class Base {
public:
int publicVar;
void publicMethod() {
cout << "Public Method" << endl;
}

private:
int privateVar;
void privateMethod() {
cout << "Private Method" << endl;
}

protected:
int protectedVar;
void protectedMethod() {
cout << "Protected Method" << endl;
}
};

class Derived : public Base {


public:
void accessMethods() {
publicVar = 1; // Accessible
publicMethod(); // Accessible

// privateVar = 2; // Not accessible


// privateMethod(); // Not accessible

protectedVar = 3; // Accessible
protectedMethod(); // Accessible
}
};
int main() {
Base base;
Derived derived;

base.publicVar = 5; // Accessible
base.publicMethod(); // Accessible

// base.privateVar = 10; // Not accessible


// base.privateMethod(); // Not accessible

// base.protectedVar = 15; // Not accessible


// base.protectedMethod(); // Not accessible

derived.accessMethods(); // Access through derived class


return 0;
}

STATIC MEMBERS IN C++:

Classes can contain static member data and member functions. When a data
member is declared as static, only one copy of the data is maintained for all
objects of the class.

Static data members are not part of objects of a given class type.

As a result, the declaration of a static data member is not considered a


definition.

The data member is declared in class scope, but definition is performed at


file scope. These static members have external linkage.

The following example illustrates this:

// static_data_members.cpp

class BufferedOutput
{
public:
// Return number of bytes written by any object of this class.
short BytesWritten()
{
return bytecount;
}
// Reset the counter.
static void ResetCount()
{
bytecount = 0;
}

// Static member declaration.


static long bytecount;
};

// Define bytecount in file scope.


long BufferedOutput::bytecount;

int main()
{
}

Constructors
A constructor is a special member function that is called automatically when
an object is created.
In C++, a constructor has the same name as that of the class, and it does not
have a return type. For example,

class Wall {
public:
// create a constructor
Wall() {
// code
}
};

Here, the function Wall() is a constructor of the class Wall . Notice that the
constructor
 has the same name as the class,

 does not have a return type, and


 is public

Default Constructor
A constructor with no parameters is known as a default constructor. For
example,
// C++ program to demonstrate the use of default constructor

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;

public:
// default constructor to initialize variable
Wall()
: length{5.5} {
cout << "Creating a wall." << endl;
cout << "Length = " << length << endl;
}
};

int main() {
Wall wall1;
return 0;
}
Run Code

Output

Creating a Wall
Length = 5.5

Parameterized Constructor
In C++, a constructor with parameters is known as a parameterized constructor. This
is the preferred method to initialize member data. For example,

// C++ program to calculate the area of a wall

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;

public:
// parameterized constructor to initialize variables
Wall(double len, double hgt)
: length{len}
, height{hgt} {
}

double calculateArea() {
return length * height;
}
};

int main() {
// create object and initialize data members
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);

cout << "Area of Wall 1: " << wall1.calculateArea() << endl;


cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;
}

Output
Area of Wall 1: 90.3
Area of Wall 2: 53.55

Copy Constructor
The copy constructor in C++ is used to copy data from one object to another.
For example,

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;

public:

// initialize variables with parameterized constructor


Wall(double len, double hgt)
: length{len}
, height{hgt} {
}

// copy constructor with a Wall object as parameter


// copies data of the obj parameter
Wall(const Wall& obj)
: length{obj.length}
, height{obj.height} {
}

double calculateArea() {
return length * height;
}
};
int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);

// copy contents of wall1 to wall2


Wall wall2 = wall1;

// print areas of wall1 and wall2


cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;
}
Run Code

Output

Area of Wall 1: 90.3


Area of Wall 2: 90.3

Destructors
A destructor is a special member function that is called automatically when
an object goes out of scope or when we delete the object with the delete
expression.
In C++, a destructor has the same name as that of the class, and it does not
have a return type. ~ precedes the identifier to indicate destructor. For
example,

class Wall {
public:
// create a destructor
~Wall() {
// code
}
};

Here, ~Wall() is a destructor of the class Wall .

EXAMPLE:

The below code demonstrates the automatic execution of constructors and


destructors when objects are created and destroyed, respectively.

#include <iostream>
using namespace std;

class Test {
public:

// User-Defined Constructor
Test() {
cout << "Constructor Called" << endl;
}

// User-Defined Destructor
~Test() {
cout << "Destructor Called" << endl;
}
};
main() {
Test t;

return 0;
}

Output

Constructor Called
Destructor Called

You might also like