Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Functions, Classes, and Objects in C++: A Comprehensive Guide, Study notes of Programming Languages

A comprehensive overview of functions, classes, and objects in c++. It covers key concepts such as function prototyping, call by value and reference, inline functions, function overloading, and the use of arrays with functions. The document also delves into the fundamentals of classes and objects, including their definitions, memory allocation, member functions, and static members. It explores the concepts of nesting member functions, private member functions, and constant member functions. The document concludes with a discussion of local classes and object manipulation, including returning objects from functions and using objects as function arguments.

Typology: Study notes

2023/2024

Available from 12/17/2024

myraa
myraa 🇮🇳

6 documents

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Page | 1
Unit II
1. Functions in C++
Dividing a program into functions is one of the major principles of top-down,
structured programming
Reduces size of program
Example:
void show();
void main()
{ …….
show();
……..
}
void show()
{ ………
}
2. The Main function
Every C++ program must have a main function
A C++ program can have any number of functions but if it has only one function it
has to be the main function.
Execution of the program begins at the main function.
In C++, the main function returns a value of the type int to the operating system
3. Function prototyping
Declaration statement of a function
Syntax:
type function-name (argument list);
Names of arguments are optional in function prototyping but mandatory in function
definition
Examples of prototyping:
float volume(int x, int y, float z);
float volume(int , int , float);
4. Call By Value
void swapv(int,int);
void main( )
{ int a=10,b=20;
swapv(a,b);
cout<<a<<“ “<<b;
}
void swapv(int x,int y)
{ int t;
t=x;
x=y;
y=t;
cout<<“\n”<<x<<“ “<<y;
}
Output:
20 10
10 20
5. Call By Reference/Address
void swapr(int *,int *);
void main( )
{ int a=10,b=20;
swapr(&a, &b);
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Functions, Classes, and Objects in C++: A Comprehensive Guide and more Study notes Programming Languages in PDF only on Docsity!

Unit II

1. Functions in C++

■ Dividing a program into functions is one of the major principles of top-down, structured programming ■ Reduces size of program ■ Example: void show(); void main() { ……. show(); …….. } void show() { ……… }

2. The Main function

■ Every C++ program must have a main function ■ A C++ program can have any number of functions but if it has only one function it has to be the main function. ■ Execution of the program begins at the main function. ■ In C++, the main function returns a value of the type int to the operating system

3. Function prototyping

■ Declaration statement of a function ■ Syntax: type function-name (argument list); ■ Names of arguments are optional in function prototyping but mandatory in function definition ■ Examples of prototyping: float volume(int x, int y, float z); float volume(int , int , float);

4. Call By Value

void swapv(int,int); void main( ) { int a=10,b=20; swapv(a,b); cout<<a<<“ “<<b; } void swapv(int x,int y) { int t; t=x; x=y; y=t; cout<<“\n”<<x<<“ “<<y; } Output: 20 10 10 20

5. Call By Reference/Address

void swapr(int *,int *); void main( ) { int a=10,b=20; swapr(&a, &b);

cout<<“\n”<<a<<“ “<<b; } void swapr(int x, int y) { int t; t=x; x=y; y=t; cout<<x<<“ “<<y; } Output: 20 10 20 10

6. Return by Reference

■ A function can also return a reference ■ Example: int & max(int &x, int &y) { if(x>y) return x; else return y; } void main() { int a=5,b=10; max(a,b)=-1; //is legal cout<<a<<“ “<<b; } //Assigns - 1 to a if it is larger otherwise - 1 to b

7. Questions

Q.1) What are Functions In C++? Why are they used? Q.2) Explain about the Main Function in a C++ program. Q.3) What is Function Prototyping? Q.4) Write a C++ program to implement Call by Reference. Q.5) Write a C++ program to implement Call by Address. Q.6) Write a C++ program to implement Call by Value. Q.7) Write a C++ program to implement Return by Reference.

8. Inline Function

■ When a function is small and called many times, a substantial percentage of execution time may be spent in overheads ■ Inline function is a function that is expanded in line when it is invoked ■ Inline function must be defined before calling inline return_type function_name(arguments) { function_body }

9. Default arguments

■ Assign a default value to the parameter, which does not have matching argument in the function call. Default values are specified when the function is declared. Eg : float amount(float principal, int period, float rate=0. 15); Function call is Value=amount(5000,7);

cout << "Student "<< i + 1 <<": "<< m[i] << endl; } } Output: Displaying marks: Student 1: 88 Student 2: 76 Student 3: 90 Student 4: 61 Student 5: 69

14. String Functions

Function

Syntax (or)

Example

Description

strcpy() strcpy(string1, string2) Copies string2 value into string strncpy() strncpy(string1, string2, 5) Copies first 5 characters string2 into string strlen() strlen(string1) returns total number of characters in string strcat() strcat(string1,string2) Appends string2 to string strncat() strncat(string1, string2,

Appends first 4 characters of string2 to string

15. Questions

Q.1) What are Inline Functions In C++? Why are they used? Q.2) Explain Default Arguments. How are they used in C++? Q.3) What are Constant Arguments? When are they used in programming? Q.4) Explain the concept of Function Overloading. Q.5) Write a C++ program to use Function with Array. Q.6) What is recursion? Explain with an example. Q.7) Explain the various string functions used in C++. .

16. Classes and Objects

Classes are user defined data types for representing a collection of objects. Syntax: class class_name { private: variable declarations; function declarations; public: variable declarations;

function declarations; }; ■ Class variables are known as objects ■ Objects can be created by: class_name variable_name; ■ Example: class xy { int x; public: int y; }; void main() { xy p; p.x=0; //error p.y=10; } Class ■ User defined data type ■ Represents collection of objects ■ No memory is allocated when a class is created ■ Comprises of data members and member functions ■ Can exist without an object Object ■ Class variable ■ Represents an instance of a class ■ Memory allocation takes place when objects are created ■ Basic run time entities ■ Cannot exist without a class Class ■ Used for holding data and functions ■ Provides data hiding ■ Declaration is done with class keyword ■ Supports inheritance Structure ■ Used for holding data only ■ Does not provide data hiding ■ Declaration is done with struct keyword ■ Does not support inheritance

17. A Sample C++ Program with class

class Hello { public: void sayHello() { cout << "Hello World" << endl; } }; int main() { Hello h; h.sayHello(); return 0; }

18. Defining Member Functions

■ Member functions can be defined:

  • Inside the class definition

void set::display() { cout<<“\nLargest=“<<largest(); } void main() { set A; A.input(); A.display(); } OUTPUT: Enter two nos. 5 3 Largest=

22. Private Member Functions

A function declared inside the class's private section is known as "private member function". A private member function is accessible through the only public member function. Example: class Student { private: int rNo; float perc; //private member functions void inputOn(void) { cout<<"Input start..."<<endl; } void inputOff(void) { cout<<"Input end..."<<endl; } public: //public member functions void read(void) { //calling first member function inputOn(); //read rNo and perc cout<<"Enter roll number: "; cin>>rNo; cout<<"Enter percentage: "; cin>>perc; //calling second member function inputOff(); } void print(void) { cout<<endl; cout<<"Roll Number: "<<rNo<<endl; cout<<"Percentage: "<<perc<<"%"<<endl; }

//Main code int main() { //declaring object of class student Student std; //reading and printing details of a student std.read(); std.print(); return 0; }

23. Arrays within a Class

  • Arrays can be declared as the members of a class.
  • The arrays can be declared as private, public or protected members of the class.
  • Example: const int size=5; class student { int roll_no; int marks[size]; public: void getdata (); void tot_marks (); } ; void student :: getdata () { cout<<"\nEnter roll no: "; cin>>roll_no; for(int i=0; i<size; i++) { cout<<"Enter marks in subject"<<(i+1)<<": "; cin>>marks[i] ; } void student :: tot_marks() //calculating total marks { int total=0; for(int i=0; i<size; i++) total+ = marks[i]; cout<<"\n\nTotal marks "<<total; } void main() { student stu; stu.getdata() ; stu.tot_marks() ; getch(); }

24. Memory Allocation for Objects

■ Once class is defined it will not allocate memory space for the data member of the class. ■ The memory allocation for the data member of the class is performed separately each time when an object of the class is created.

■ In order to make a member function as static we need to precede the function declaration with static keyword. ■ Example: #include <iostream.h> #include <conio.h> class test { private: static int count; public: void setCount(void); static void DisplayCounter(void); }; void test :: setCount(void) { count++; } void test :: DisplayCounter(void) { cout<< count << endl; } int test::count; void main() { test t1, t2; clrscr(); t1.setCount(); test :: DisplayCounter(); t2.setCount(); test :: DisplayCounter(); getch(); } Output: 1 2

27. Questions

Q.1) How can member functions be nested? Q.2) What are private member functions? How can they be used? Q.3) Write a C++ program to demonstrate use of arrays within a class. Q.4) How is memory allocation done for objects? Q.5) What are static data members? Q.6) What are static member functions?

28. Array of Objects

■ An object of class represents a single record in memory, if we want more than one record of class type, we have to create an array of class or object. ■ An array is a collection of similar type, therefore an array can be a collection of class type. ■ Syntax: class class_name { datatype var1; datatype var2;


datatype varN;

method1(); method2();


methodN(); }; class_name obj[ size ]; ■ Example for Array of object #include<iostream.h> #include<conio.h> class Employee { int Id; char Name[25]; int Age; long Salary; public: void GetData() { cout<<"\n\tEnter Employee Id : "; cin>>Id; cout<<"\n\tEnter Employee Name : "; cin>>Name; cout<<"\n\tEnter Employee Age : "; cin>>Age; cout<<"\n\tEnter Employee Salary : "; cin>>Salary; } void PutData() { cout<<"\n"<<Id<<"\t"<<Name<<"\t"<<Age<<"\t"<<Salary; } }; void main() { int i; clrscr(); Employee E[3]; for(i=0;i<3;i++) { cout<<"\nEnter details of "<<i+1<<" Employee"; E[i].GetData(); } cout<<"\nDetails of Employees"; for(i=0;i<3;i++) E[i].PutData(); getch(); }

29. Objects as Function Arguments

■ return_type function name(type var1,type var2..) ■ Create a class called rational having two data members num and dnum and three functions get(),print() and divide(). The divide function must take two arguments that are objects of the rational class and perform division of rational numbers. #include<iostream.h> #include<conio.h> class rational { int num;

public: void setvalue(int i) { a=i; } friend void max(XYZ,ABC); }; void max(XYZ m,ABC n) { if (m.x>n.a) cout<<m.x; else cout<<n.a; } void main( ) { ABC abc; clrscr(); abc.setvalue(10); XYZ xyz; xyz.setvalue(20); max(xyz,abc); getch(); }

32. Returning Objects

■ Objects can be returned from functions. The following code illustrates this concept: class circle { float r; public: void getradius() { cout<<"Enter radius:"; cin>>r; } void area() { float a; a=3.14rr; cout<<"\tArea="<<a; } circle Sum(circle c) { circle temp; temp.r = r + c.r; return temp; } void Display() { cout<<r; } }; void main() { circle c1,c2,c3; clrscr(); c1.getradius(); c2.getradius(); cout<<"\n\nValue of radius of circle 1 : "; c1.Display(); c1.area(); cout<<"\n\nValue of radius of circle 2 : "; c2.Display(); c2.area(); c3 = c1.Sum(c2);

cout<<"\n\nValue of radius of circle 3 : "; c3.Display(); c3.area(); getch(); }

33. Constant Member Functions

A const or a constant member function can only read or retrieve the data members of the calling object without modifying them. If such a member function attempts to modify any data member of the calling object, a compile-time error is generated. The syntax for defining a const member function is: return_type function_name (parameter_list) const { //body of the member function } ■ If a member function does not alter any data in the class then it may be declared as const member function as follows: ■ Syntax: return_type function_name(parameter list) const; ■ Example: void mul (int,int) const; void get_balance() const; ■ The qualifier const is appended to the function prototypes in both declaration and definition ■ The compiler will generate an error message if such functions try to alter the data values. ■ Example: #include<iostream.h> #include<conio.h> class Employee { int Id; char Name[25]; int Age; long Salary; public: void GetData() { cout<<"\n\tEnter Employee Id : "; cin>>Id; cout<<"\n\tEnter Employee Name : "; cin>>Name; cout<<"\n\tEnter Employee Age : "; cin>>Age; cout<<"\n\tEnter Employee Salary : "; cin>>Salary; } void PutData() const { cout<<"\n"<<Id<<"\t"<<Name<<"\t"<<Age<<"\t"<<Salary; } }; void main() { int i; clrscr(); Employee E[3]; for(i=0;i<3;i++)