0% found this document useful (0 votes)
25 views

user defiend datatypes in c++

Uploaded by

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

user defiend datatypes in c++

Uploaded by

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

USER DEFINED DATA TYPES

Structure is a group of variables of different data types represented by a single name.


It is a user defined datatype.

OR

Structure is the collection of dissimilar data types or heterogeneous data types


grouped together. It means the data types may or may not be of same type. It is user
defined data type.

Lets take an example to understand the need of a structure in C programming.

Lets say we need to store the data of students like student name, age, address, id etc.
One way of doing this would be creating a different variable for each attribute,
however when you need to store the data of multiple students then in that case, you
would need to create these several variables again for each student. This is such a big
headache to store data in this way.

We can solve this problem easily by using structure. We can create a structure that
has members for name, id, address and age and then we can create the variables of
this structure for each student. This may sound confusing, do not worry we will
understand this with the help of example.

How to create a structure in C Programming

We use struct keyword to create a structure in C. The struct keyword is a short form
of structured data type.

struct struct_name
{ DataType member1_name;
DataType member2_name;
DataType member3_name;
… };
Here struct_name can be anything of your choice. Member data type can be same or
different. Once we have declared the structure we can use the struct name as a data
type like int, float etc.

First we will see the syntax of creating struct variable, accessing struct members etc
and then we will see a complete example.

Structure variable declaration;

struct student

int age;

char name[20];

char branch[20];

};

struct student s;

OR

How to declare variable of a structure?

struct struct_name var_name;


or

struct struct_name
{ DataType member1_name;
DataType member2_name;
DataType member3_name; … } var_name;
How to access data members of a structure using a struct variable?

var_name.member1_name; var_name.member2_name; …

Initialization of structure variable-

Like primary variables structure variables can also be initialized when they are
declared. Structure templates can be defined locally or globally. If it is local it can be
used within that function. If it is global it can be used by all other functions of the
program.
We can’t initialize structure members while defining the structure

struct student{

int age=20;

char name[20]=”sona”;

} s1;

The above is invalid.

A structure can be initialized as

struct student{

int age,roll;

char name[20];

};

struct student s1={16,101,”sona”}; int a=10;

struct student s2={17,102,”rupa”};

If initialiser is less than number of structure variable, automatically rest of the values
are taken as zero.

Structures in C++ can contain two types of members:


• Data Member: These members are normal C++ variables. We can create a
structure with variables of different data types in C++.
• Member Functions: These members are normal C++ functions. Along with
variables, we can also include functions inside a structure declaration.
• Example:
// Data Members
int roll;
int age;
int marks;

// Member Functions
void printDetails()
{
cout<<"Roll = "<<roll<<"\n";
cout<<"Age = "<<age<<"\n";
cout<<"Marks = "<<marks;

}
In the above structure, the data members are three integer variables to store roll
number, age and marks of any student and the member function is printDetails()
which is printing all of the above details of any student.

How to assign values to structure members?

There are three ways to do this.

1) Using Dot(.) operator

var_name.memeber_name = value;
2) All members assigned in one statement

struct struct_name var_name = {value for memeber1, value for memeber2 …so on
for all the members}
3) Designated initializers – We will discuss this later at the end of this post.

How to access structure elements?

Structure members are accessed using dot (.) operator.


#include <iostream>
using namespace std;

struct Point {
int x, y;
};

int main()
{
struct Point p1 = { 0, 1 };

// Accessing members of point p1


p1.x = 20;
cout << "x = " << p1.x << ", y = " << p1.y;
return 0;
}
Output:
x = 20, y = 1

Size of structure-

Size of structure can be found out using sizeof() operator with structure variable name
or tag name with keyword.

sizeof(struct student); or

sizeof(s1);
sizeof(s2);

So size of whole structure is equal to sum of size of its members.

Example of Structure in C++

#include <iostream.h> /* Created a structure here. The name of the structure is *


StudentData. */
struct StudentData
{ char *stu_name;
int stu_id;
int stu_age; };

int main()
{ /* student is the variable of structure StudentData*/
struct StudentData student; /*Assigning the values of each struct member here*/
student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30; /* Displaying the values of struct members */
cout<<"Student Name is: "<< student.stu_name;
cout<<"\nStudent Id is: "<<student.stu_id;
cout<<"\nStudent Age is:”<< student.stu_age;
return 0;
}
Output:

Student Name is: Steve


Student Id is: 1234
Student Age is: 30

Nested Structure in C++: Struct inside another struct

When a structure is within another structure, it is called Nested structure .

You can use a structure inside another structure, which is fairly possible. As I
explained above that once you declared a structure, the struct struct_name acts as a
new data type so you can include it in another struct just like the data type of other
data members. Sounds confusing? Don’t worry. The following example will clear
your doubt.

Nested structure

A structure variable can be a member of another structure and it is represented as

struct student

{
element 1;
element 2;

......... .........

struct student1

{
member 1;

member 2; }variable 1; .......... .......... element n; }variable 2;

It is possible to define structure outside & declare its variable inside other structure.

struct date

{
int date,month; };

struct student {

char nm[20];

int roll;

struct date d;

}; struct student s1;

struct student s2,s3;

Nested structure may also be initialized at the time of declaration like in above
example.

struct student s={“name”,200, {date, month}}; {“ram”,201, {12,11}};

Example of Nested Structure in C++ Programming

Lets say we have two structure like this:

Structure 1: stu_address

struct stu_address
{ int street;
char *state;
char *city;
char *country;
}
Structure 2: stu_data

struct stu_data
{ int stu_id;
int stu_age;
char *stu_name;
struct stu_address stuAddress;

}
As you can see here that I have nested a structure inside another structure.

Designated initializers to set values of Structure members

We have already learned two ways to set the values of a struct member, there is
another way to do the same using designated initializers. This is useful when we are
doing assignment of only few members of the structure. In the following example the
structure variable s2 has only one member assignment.

#include <iostream.h>
struct numbers { int num1, num2; };
int main()
{ // Assignment using using designated initialization
struct numbers s1 = {.num2 = 22, .num1 = 11};
struct numbers s2 = {.num2 = 30};
cout<<"num1: “<<s1.num1<<”,num2:”<< s1.num2: <<”\n";
cout<<"num1:"<< s2.num2;
return 0;
}
Output:

num1: 11, num2: 22


num1: 30
UNION

Union is user defined data type which contains collection of different data type or
dissimilar elements. All definition, declaration of union variable and accessing
member is similar to structure, but instead of keyword struct the keyword union is
used, the main difference between union and structure is

Each member of structure occupy memory location, but in the unions members share
the memory. Memory is allotted to the largest data member. Union is used for saving
memory and concept is useful when it is not necessary to use all members of union at
a time.

Syntax of union:

union student

{
datatype member1;

datatype member2; };

Like structure variable, union variable can be declared with definition or separately
such as

union union name

{
Datatype member1;

}var1;

Example:- union student s;

Union members can also be accessed by the dot operator with union variable and if
we have pointer to union then member can be accessed by using (arrow) operator as
with structure.

Example:-

struct student

{
int i;

char ch[10];

};struct student s;

Here datatype/member structure occupy 12 byte of location in memory, where as in


the union side it occupy only 10 byte.
Nesting of Union

When one union is inside the another union it is called nesting of union. Example:-

union a{

int i; int age; };

union b {

char name[10];

union a aa;

}; union b bb;
ENUMERATED DATA TYPE IN C++

Enumeration (or enum) in C++


Enumeration (or enum) is a user defined data type in C++ It is mainly used to assign
names to integral constants, the names make a program easy to read and maintain.

enum State {Working = 1, Failed = 0};


The keyword ‘enum’ is used to declare new enumeration types in C and C++.
Following is an example of enum declaration.
Variables of type enum can also be defined. They can be defined in two ways:
// In both of the below cases, "day" is defined as the variable of type week.
enum week{Mon, Tue, Wed};
enum week day;
// Or
enum week{Mon, Tue, Wed}day;

// An example program to demonstrate working of enum in C++


#include<iostream.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()
{
enum week day;
day = Wed;
cout<<day;
return 0;
}
Output:
2
In the above example, we declared “day” as the variable and the value of “Wed” is
allocated to day, which is 2. So as a result, 2 is printed.
Another example of enumeration is:
// Another example program to demonstrate working of enum in C++
#include<iostream.h>

enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};

int main()
{
int i;
for (i=Jan; i<=Dec; i++)
cout<<i;
return 0;
}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
In this example, the for loop will run from i = 0 to i = 11, as initially the value of i is
Jan which is 0 and the value of Dec is 11.
Interesting facts about initialization of enum.

1. Two enum names can have same value. For example, in the following C program
both ‘Failed’ and ‘Freezed’ have same value 0.

#include <iostream.h>
enum State {Working = 1, Failed = 0, Freezed = 0};

int main()
{
cout<<Working<< “\n”<<Failed<< “\n”<<Freezed;
return 0;
}

Output:
1
0
0
ANOTHER EXAMPLE
// Another example program to demonstrate working of enum in C++
#include<iostream.h>

enum year{Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};

int main()
{
int i;
for (i=Jan; i<=Dec; i++)
cout<<i;
return 0;
}

Output:
1 2 3 4 5 6 7 8 9 10 11 12
Now this looks correct. So we can initialize jan=1 and rest of the months integral
constant will be incremented by 1 and we will get the correct sequence of months.

2. If we do not explicitly assign values to enum names, the compiler by default


assigns values starting from 0. For example, in the following C program, sunday gets
value 0, monday gets 1, and so on.

#include <iostream.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};

int main()
{
enum day d = thursday;
cout<<"The day number stored in d is"<< d;
return 0;
}
Output:
The day number stored in d is 4

3. We can assign values to some name in any order. All unassigned names get value
as value of previous name plus one.

#include <iostream.h>
enum day {sunday = 1, monday, Tuesday =5,wednesday, thursday = 10, friday,
saturday};

int main()
{
cout<<sunday << monday<< tuesday<< wednesday <<thursday
<<friday<<saturday;
return 0;
}
Output:
1 2 5 6 10 11 12

4. The value assigned to enum names must be some integeral constant, i.e., the value
must be in range from minimum possible integer value to maximum possible integer
value.

5. All enum constants must be unique in their scope. For example, the following
program fails in compilation.
enum state {working, failed};
enum result {failed, passed};

int main() { return 0; }


Output:
Compile Error: 'failed' has a previous declaration as 'state failed'

Structure Vs class in C++

In C++, a structure is the same as a class except for a few differences. The most
important of them is security. A Structure is not secure and cannot hide its
implementation details from the end user while a class is secure and can hide its
programming and designing details. Following are the points that expound on this
difference:
1) Members of a class are private by default and members of a struct are public by
default.
For example program 1 fails in compilation and program 2 works fine.

// Program 1
#include <iostream.h>

class Test {
int x; // x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
getchar();
return 0;
}

// Program 2
#include <iostream.h>
struct Test {
int x; // x is public
};
int main()
{
Test t;
t.x = 20; // works fine because x is public
getchar();
return 0;
}
2) When deriving a struct from a class/struct, default access-specifier for a base
class/struct is public. And when deriving a class, default access specifier is private.
For example program 3 fails in compilation and program 4 works fine.

// Program 3
#include <iostream.h>

class Base {
public:
int x;
};

class Derived : Base { }; // is equilalent to class Derived : private Base {}

int main()
{
Derived d;
d.x = 20; // compiler error becuase inheritance is private
getchar();
return 0;
}

// Program 4
#include <iostream.h>

class Base {
public:
int x;
};

struct Derived : Base { }; // is equilalent to struct Derived : public Base {}

int main()
{
Derived d;
d.x = 20; // works fine becuase inheritance is public
getchar();
return 0;
}

References in C++

When a variable is declared as reference, it becomes an alternative name for an


existing variable. A variable can be declared as reference by putting ‘&’ in the
declaration.

#include<iostream.h>

int main()
{
int x = 10;

// ref is a reference to x.
int& ref = x;

// Value of x is now changed to 20


ref = 20;
cout << "x = " << x << endl ;

// Value of x is now changed to 30


x = 30;
cout << "ref = " << ref << endl ;

return 0;
}
Output:
x = 20 ref = 30
Applications :
1. Modify the passed parameters in a function : If a function receives a
reference to a variable, it can modify the value of the variable. For example, in
the following program variables are swapped using references.

#include<iostream.h>

void swap (int& first, int& second)


{
int temp = first;
first = second;
second = temp;
}

int main()
{
int a = 2, b = 3;
swap( a, b );
cout << a << " " << b;
return 0;
}

Output:
32

References vs Pointers

Both references and pointers can be used to change local variables of one function
inside another function. Both of them can also be used to save copying of big objects
when passed as arguments to functions or returned from functions, to get efficiency
gain.
Despite above similarities, there are following differences between references and
pointers.
A pointer can be declared as void but a reference can never be void
For example
int a = 10;
void* aa = &a;. //it is valid
void &ar = a; // it is not valid
&a= address of a in memory
** aa=points to address of a
in address of a , we have stored pointer variable aa
References are less powerful than pointers
1) Once a reference is created, it cannot be later made to reference another
object; it cannot be reseated. This is often done with pointers.
2) References cannot be NULL. Pointers are often made NULL to indicate that
they are not pointing to any valid thing.
3) A reference must be initialized when declared. There is no such restriction
with pointers
Due to the above limitations, references in C++ cannot be used for implementing data
structures like Linked List, Tree, etc. In Java, references don’t have above restrictions,
and can be used to implement all data structures. References being more powerful in
Java, is the main reason Java doesn’t need pointers.
References are safer and easier to use:

1) Safer: Since references must be initialized, wild references like wild pointers are
unlikely to exist. It is still possible to have references that don’t refer to a valid
location .

2) Easier to use: References don’t need dereferencing operator to access the value.
They can be used like normal variables. ‘&’ operator is needed only at the time of
declaration. Also, members of an object reference can be accessed with dot operator
(‘.’), unlike pointers where arrow operator (->) is needed to access members.
Together with the above reasons, there are few places like copy constructor argument
where pointer cannot be used. Reference must be used pass the argument in copy
constructor. Similarly references must be used for overloading some operators like
++.

C++ Classes and Objects

Class: A class in C++ is the building block, that leads to Object-Oriented


programming. It is a user-defined data type, which holds its own data members and
member functions, which 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 brand but all of them will share some common properties like all of them
will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and
wheels, speed limits, mileage are their properties.
• A Class is a user defined data-type which has data members and member
functions.
• Data members are the data variables and member functions are the functions
used to manipulate these variables and together these data members and member
functions defines the properties and behavior of the objects in a Class.
• In the above example of class Car, the data member will be speed
limit, mileage etc and member functions can be apply brakes, increase
speed etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated
but when it is instantiated (i.e. an object is created) memory is allocated.
Class cars
{
}
class cars c1;

A class is defined in C++ using keyword class followed by the name of class. The
body of class is defined inside the curly brackets and terminated by a semicolon at the
end.

a class has 3 access specifiers


public, private, protected

Declaring Objects: When a class is defined, only the specification for the object is
defined; no memory or storage is allocated. To use the data and access functions
defined in the class, you need to create objects.
Syntax:
ClassName ObjectName;
Accessing data members and member functions: The data members and member
functions of class can be accessed using the dot(‘.’) operator with the object. For
example if the name of object is obj and you want to access the member function with
the name printName() then you will have to write obj.printName() .
Accessing Data Members
The public data members are also accessed in the same way given however the
private data members are not allowed to be accessed directly by the object. Accessing
a data member depends solely on the access control of that data member.
This access control is given by Access modifiers in C++. There are three access
modifiers : public, private and protected.

// C++ program to demonstrate accessing of data members

#include <iostream.h>

class Geeks
{
// Access specifier
public:

// Data Members
string geekname;

// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}
};

geeks
string geekname
void printname

int main()
{

// Declare an object of class geeks


Geeks obj1;

// accessing data member


obj1.geekname = "Abhi";

// accessing member function


obj1.printname();
return 0;
}
Output:
Geekname is: Abhi

Member Functions in Classes


There are 2 ways to define a member function:
• Inside class definition
• Outside class definition
To define a member function outside the class definition we have to use the scope
resolution :: operator along with class name and function name.

// C++ program to demonstrate function declaration outside class

#include <iostream.h>

class Geeks
{
public:
string geekname;
int id;

// printname is not defined inside class definition


void printname();

// printid is defined inside class definition


void printid()
{
cout << "Geek id is: " << id;
}
};

// Definition of printname using scope resolution operator ::


void Geeks::printname()
{
cout << "Geekname is: " << geekname;
}
int main() {

Geeks obj1;
obj1.geekname = "xyz";
obj1.id=15;

// call printname()
obj1.printname();
cout << endl;

// call printid()
obj1.printid();
return 0;
}
Output:
Geekname is: xyz
Geek id is: 15
Note that all the member functions defined inside the class definition are by default
inline, but you can also make any non-class function inline by using keyword inline
with them. Inline functions are actual functions, which are copied everywhere during
compilation, like pre-processor macro, so the overhead of function calling is reduced.

REFERENCES:

1. Structure in C programming with examples BY CHAITANYA


SINGH | FILED UNDER: C-PROGRAMMING
2. Geeksforgeeks.org
Examples

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

void main()
{
struct book1
{
char book[30];
int pages;
float price;
};
struct book1 bk1={“C++”, 300};
clrscr();
cout<<”enter the book name”<<bk1.book;
cout<<”enter the no. of pages”<< bk1.pages;
cout<<”enter the price of book”;
cin>>bk1.price;
cout<<”total size of structure book1=”<<sizeof(bk1);
getch();
}

output
enter the book name “JAVA
enter the no. of pages 400
enter the price of book 505.67
total size of structure book1=38

UNION
#include<iostream.h>
#include<conio.h>

void main()
{
union result
{
int marks;
char grade;
};
struct res
{
char name[15];
int age;
union result perf;
}data;
clrscr();
cout<<”size of union=”<<sizeof(data.perf);
cout<<”size of structure=”<<sizeof(data);
getch();
}

output
size of union=4
size of structure=23

CLASSES- showing the difference between public and private data members
Strucuture-everything is public/visible
Classes- everything is private/not visible/not accessible until you make it
PUBLIC

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

class player
{
private:
char name[20];
int age;
public:
float height, weight;
//PUBLIC FUNCTION
};

int main()
{
clrscr();
class player a;
a.height=5.5;
a.weight=50;
cout<<”height=”<<a.height;
cout<<”weight=”<<a.weight;
return 0;
}
Declare class with member variables and functions
#include<iostream.h>
#include<conio.h>

class player
{ private:
char name[20];
int age;
float height, weight;
public:
void setdata()
{
cout<<”Enter the name, age, height and weight \n”;
cin>>name>>age>>height>>weight;
}
void showdata()
{
cout<<”\n name=”<<name;
cout<<”\n Age=”<<age;
cout<<”\n height=”<<height;
cout<<”\n weight=”<<weight;
}

};

int main()
{
clrscr();
class player a;
a.setdata();
a.showdata();
return 0;
}

CLASSES- showing function definition outside the class


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

class player
{ private:
char name[20];
int age;
float height, weight;
public:
void setdata();
void showdata();
};
void player : : setdata() : : SCOPE RESOLUTION OPERATOR
{
cout<<”Enter the name, age, height and weight \n”;
cin>>name>>age>>height>>weight;
}
void player : : showdata()
{
cout<<”\n name=”<<name;
cout<<”\n Age=”<<age;
cout<<”\n height=”<<height;
cout<<”\n weight=”<<weight;
}

int main()
{
clrscr();
class player a;
a.setdata();
a.showdata();
return 0;
}

POINTERS
#include<iostream.h>
#include<conio.h>

void main()
{int v=10, *p;
clrscr();
p=&v;
cout<<”\n Address of v=”<<p;
cout<<”\n Value of v=”<<*p;
cout<<”\n Address of p=”<<&p;
getch();
}

OUTPUT
Address of v=4060
Value of v=10
Address of p=4064

ADDRESS 4060 4064 4068 4072 4076


VALUE/NAME V=10 P=4060

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy