user defiend datatypes in c++
user defiend datatypes in c++
OR
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.
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.
struct student
int age;
char name[20];
char branch[20];
};
struct student s;
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; …
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;
struct student{
int age,roll;
char name[20];
};
If initialiser is less than number of structure variable, automatically rest of the values
are taken as zero.
// 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.
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.
struct Point {
int x, y;
};
int main()
{
struct Point p1 = { 0, 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);
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:
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
struct student
{
element 1;
element 2;
......... .........
struct student1
{
member 1;
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;
Nested structure may also be initialized at the time of declaration like in above
example.
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.
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:
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
{
Datatype member1;
}var1;
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;
When one union is inside the another union it is called nesting of union. Example:-
union a{
union b {
char name[10];
union a aa;
}; union b bb;
ENUMERATED DATA TYPE IN C++
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.
#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};
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;
};
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;
};
int main()
{
Derived d;
d.x = 20; // works fine becuase inheritance is public
getchar();
return 0;
}
References in C++
#include<iostream.h>
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
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>
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
++.
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.
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.
#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()
{
#include <iostream.h>
class Geeks
{
public:
string geekname;
int id;
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:
#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;
}
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