Showing posts sorted by relevance for query Functions. Sort by date Show all posts

Classes and Objects

Classes and Objects

C++ Class

  • Before you create an object in C++, you need to define a class.
  • A class is a blueprint for the object.
  • We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
  • As, many houses can be made from the same description, we can create many objects from a class.


How to define a class in C++?

  • 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.

class className
   {
   // some data
   // some functions
   };

Example: Class in C++

class Test
{
    private:
        int data1;
        float data2;  

    public:  
        void function1()
        {   data1 = 2;  } 

        float function2()
        { 
            data2 = 3.5;
            return data2;
        }
   };
  • Here, we defined a class named Test.
  • This class has two data members: data1 and data2 and two member functions: function1() and function2().


Keywords: private and public

You may have noticed two keywords: private and public in the above example.
  • The private keyword makes data and functions private. Private data and functions can be accessed only from inside the same class.
  • The public keyword makes data and functions public. Public data and functions can be accessed out of the class.

Here, data1 and data2 are private members where as function1() and function2() are public members.
If you try to access private data from outside of the class, compiler throws error. This feature in OOP is known as data hiding.

C++ Objects

  • When 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 to Define Object in C++

className objectVariableName;
  • You can create objects of Test class (defined in above example) as follows:


class Test
{
    private:
        int data1;
        float data2;  

    public:  
        void function1()
        {   data1 = 2;  } 

        float function2()
        { 
            data2 = 3.5;
            return data2;
        }
   };

int main()
{
    Test o1, o2;
}
Here, two objects o1 and o2 of Test class are created.
In the above class Testdata1 and data2 are data members and function1() and function2() are member functions.

How to access data member and member function in C++?

  • You can access the data members and member functions by using a . (dot) operator. For example,

o2.function1();
This will call the function1() function inside the Test class for objects o2.
Similarly, the data member can be accessed as:
o1.data2 = 5.5;
It is important to note that, the private members can be accessed only from inside the class.
So, you can use o2.function1(); from any function or class in the above example. However, the code o1.data2 = 5.5; should always be inside the class Test.

Example: Object and Class in C++ Programming

// Program to illustrate the working of objects and class in C++ Programming
#include <iostream.h>
#include<conio.h>

class Test
{
    private:
        int data1;
        float data2;

    public:
       
       void insertIntegerData(int d)
       {
          data1 = d;
          cout << "Number: " << data1;
        }

       float insertFloatData()
       {
           cout << "\nEnter data: ";
           cin >> data2;
           return data2;
        }
};

 int main()
 {
      Test o1, o2;
      float secondDataOfObject2;

      o1.insertIntegerData(12);
      secondDataOfObject2 = o2.insertFloatData();

      cout << "You entered " << secondDataOfObject2;
      return 0;
 }
Output
Number: 12
Enter data: 23.3
You entered 23.3
  • In this program, two data members data1 and data2 and two member functions insertIntegerData() and insertFloatData() are defined under Test class.

Two objects o1 and o2 of the same class are declared.
The insertIntegerData() function is called for the o1 object using:
o1.insertIntegerData(12);
  • This sets the value of data1 for object o1 to 12.

Then, the insertFloatData() function for object o2 is called and the return value from the function is stored in variable secondDataOfObject2 using:
secondDataOfObject2 = o2.insertFloatData();
In this program, data2 of o1 and data1 of o2 are not used and contains garbage value.

Function

Function

#A function is a group of statements that together perform a specific task. Every C program has at least one function, which is main().

Why use function ?

Function are used for divide a large code into module, due to this we can easily debug and maintain the code. For example if we write a calculator programs at that time we can write every logic in a separate function (For addition sum(), for subtraction sub()). Any function can be called many times.

Advantage of Function

  • Code Re-usability
  • Develop an application in module format.
  • Easily to debug the program.
  • Code optimization: No need to write lot of code.

Type of Function

There are two type of function in C Language. They are;
  • Library function or pre-define function.
  • User defined function.

Library function

Library functions are those which are predefined in C compiler. The implementation part of pre-defined functions is available in library files that are .lib/.obj files. .lib or .obj files are contained pre-compiled code. printf(), scanf(), clrscr(), pow() etc. are pre-defined functions.

Limitations of Library function

  • All predefined function are contained limited task only that is for what purpose function is designed for same purpose it should be used.
  • As a programmer we do not having any controls on predefined function implementation part is there in machine readable format.
  • In implementation whenever a predefined function is not supporting user requirement then go for user defined function.

User defined function

These functions are created by programmer according to their requirement for example suppose you want to create a function for add two number then you create a function with name sum() this type of function is called user defined function.

Defining a function.

Defining of function is nothing but give body of function that means write logic inside function body.

Syntax

 
return_type  function_name(parameter)
{
function body;
}
  • Return type: A function may return a value. The return_type is the data type of the value the function returns.Return type parameters and returns statement are optional.
  • Function name: Function name is the name of function it is decided by programmer or you.
  • Parameters: This is a value which is pass in function at the time of calling of function A parameter is like a placeholder. It is optional.
  • Function body: Function body is the collection of statements.

Function Declarations

A function declaration is the process of tells the compiler about a function name. The actual body of the function can be defined separately.

Syntax

return_type  function_name(parameter);
Note: At the time of function declaration function must be terminated with ;.

calling a function.

When we call any function control goes to function body and execute entire code. For call any function just write name of function and if any parameter is required then pass parameter.

Syntax

function_name(); 
    or  
variable=function_name(argument);  
Note: At the time of function calling function must be terminated with ';'.

Example of Function

 
#include<stdio.h>
#include<conio.h>

void sum(); // declaring a function
clrsct();
int a=10,b=20, c;

void sum()  // defining function
{
c=a+b;
printf("Sum: %d", c);
}
void main()
{
sum();  // calling function
}

Output

 
Sum: 30

Structure of basic C program

Structure of C Program

#Every C program can be written with the following syntax.

Syntax

#include<headerfilename.h>  --> include section
Returntype function_name(list of parameters or no parameter)  --> user defined function
{
Set of statements
.........
}
Returntype main()  --> main block or main function
{
.........
.........
}

Include section

# include is a pre-processor directive can be used to include all the predefined functions of given header files into current C program before compilation.

Syntax

#include<headerfile.h>
C library is collection of header files, header files is a container which is collection of related predefined functions.

User defined function section

If any function is defined by the user is known as user defined function. Function is collection of statement used to perform a specific Operation.

Syntax

Return_type function_Name()
{
....... // called function
.......
}
In the above syntax function name can be any user defined name, return type represents which type of value it can return to its calling function.

Syntax

functionName(); // calling function
Note: User defined function are Optional in a C program.

Main function

This is starting executable block of any program (it is always executed by processor and OS ). One C program can have maximum one main() the entire statements of given program can be executed through main(). Without main() function no C program will be executed.

Syntax

Returntype main()
{
......
.....
}
If return type is void that function can not return any value to the operating system. So that void can be treated as no return type.

Example

#include<stdio.h>
#include<conio.h>

void main()
{
printf("Hello main");
}

Output

Hello main

IO statements in C language

IO represents input output statements and input statement can be used to read the input value from the standard input device (keyboard), output statement can be used to display the output in standard output device (Monitor) respectively. In C language IO statement can be achieve by using scanf() and printf().

Scope of variables

Difference between Local variable and Global variable

#In C language, a variable can be either of global or local scope.

Global variable

Global variables are defined outside of all the functions, generally on top of the program. The global variables will hold their value throughout the life-time of your program.

Local variable

A local variable is declared within the body of a function or a block. Local variable only use within the function or block where it is declare.

Example of Global and Local variable

Example

#include<stdio.h>
#include<conio.h>

int a;   // global variable
void main()
{
int b;    // local variable
a=10, b=20;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
getch();
}

Output

Value of a: 10
Value of b: 20

String in C

String

#String is a collection of character or group of character, it is achieve in C language by using array character. The string in C language is one-dimensional array of character which is terminated by a null character '\0'. In other words string is a collection of character which is enclose between double cotes ( " " ).
Note: Strings are always enclosed within double quotes. Whereas, character is enclosed within single quotes in C.

Declaration of string

Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type.

Example

 
char s[5];

Initializing Array string

String are initialize into various way in c language;

Example

char str[]="abcd";
        OR
char str[5]="abcd";
        OR
char str[5]={'a','b','c','d','\0'};
        OR
char str[]={'a','b','c','d','\0'};
        OR
char str[5]={'a','b','c','d','\0'};
In c language string can be initialize using pointer.

Example

char *c="abcd";

Reading String from user

Example

 
char str[5];
scanf("%s",&str);

Example

 
#include<stdio.h>
#include<conio.h>

void main()
{
char str[10];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is: %s.",name);
getch();
}

Example of reading string

 
Enter name: Hitesh kumar
Your name is: Hitesh
Note: String variable str can only take only one word. It is because when white space is encountered, the scanf() function terminates. to over come this problem you can use gets() function.

Syntax

 
char str[5];
gets(str);

gets()

gets() are used to get input as a string from keyword, using gets() we can input more than one word at a time.

puts()

puts() are used to print output on screen, generally puts() function are used with gets() function.

Example of String program

#include<stdio.h>
#include<conio.h>

void main()
{
char str[10];
printf("Enter any string: ");
gets(str);
printf("String are: ");
puts(str);
getch();
}
Explanation: Here gets() function are used for input string and puts() function are used to show string on console or monitor.

Output

Enter String: hello word
String are: hello word

C Library String functions

All the library function of String is available in String.h header file.
S.N.FunctionPurpose
1strcpy(s1, s2)Copies string s2 into string s1.
2strcat(s1, s2)Concatenates string s2 onto the end of string s1.
3strlen(s1)Returns the length of string s1.
4strcmp(s1, s2)Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5strchr(s1, ch)Returns a pointer to the first occurrence of character ch in string s1.
6strstr(s1, s2)Returns a pointer to the first occurrence of string s2 in string s1.

Important points for Declaration of string

  • In declaration of string size must be required to mention otherwise it gives an error.

Syntax

char str[];   // Invalid
char str[10]; // Valid
  • In declaration of the string size must be unsigned integer value (not -ve or zero value) which is greater than zero only.

Example

char str[];   // Invalid
char str[0];  // Invalid
char str[-1]; // Invalid
char str[10]; // Valid

Syntax

 
char variable_name[SIZE];
 
char str[5];

Important points for Initialization of the string

  • In Initialization of the string if the specific number of character are not initialized it then rest of all character will be initialized with NULL.

Example

char str[5]={'5','+','A'};
    str[0];  ---> 5
    str[1];  ---> +
    str[2];  ---> A
    str[3];  ---> NULL
    str[4];  ---> NULL
  • In initialization of the string we can not initialized more than size of string elements.

Example

 
char str[2]={'5','+','A','B'};  // Invalid
  • In initialization of the string the size is optional in this case how many variable elements are initialized it, that array element will created.

Example

 
char str[]={'5','+','A','B'};  // Valid
sizeof(str)  --> 4byte
When we are working with character array explicitly NULL character does not occupies any physical memory at the end of the character array.

Example

char str[]={'h','e','l','l','o'};
sizeof(str)  --> 5byte
String data at the end of the string NULL character occupies physical memory.

Example

char str[]="hello";
sizeof(str)  --> 6 byte