You are on page 1of 4

OBJECT ORIENTED PROGRAMMING WITH C++

UNIT 1

Structure in C
1. A structure is a collection of variables referenced under one name i.e. structure name, providing a convenient means of keeping related information together. 2. The keyword struct tells the compiler that a structure is being declared. 3. The elements of structure are called structure elements or members. SYNTAX: Struct structure_name { Data_type member 1; Data_type member 2; ..; ; }; Example:struct book_bank { char title[30]; char author[10]; int pages; float price; };

Accessing members of structure using structure variable

Page | 1

In C, to declare a variable(i.e. a physicl object) of structure type, write struct structure_name variable_name; Example:struct book_bank { char title[30]; char author[10]; int pages; float price; }; main() { struct book_bank book1, book2; .; .; } It declares book1, book2 as structure variables of the structure book_bank. In C++ we me declare variables directly no struct keyword is required book_bank book1,book2; We may also declare one or more variables when we declare variables struct book_bank { char title[30]; char author[10]; int pages;

Page | 2

float price; }book1,book2;

Passing structures to functions


1. Passing structure members to function When we pass a member of a structure to function, we are actually passing the value of that member to the function. struct demo { char x; int y; }d1;

func(d1.x); func1(d1.y);

/*passes character value of x */ /*passes integer value of y*/

2. Passing entire structure to the function When a structure is used as an argument to a function, the entire structure is passed using the call-by-value method i.e. any changes made to the content of structure inside the function to which it is passed do not affect the structure used as an argument. Syntax:data-type function_name(structure_name parameters); example:#include<stdio.h> /*define structure*/ Struct complex { Page | 3

Float imag,real; }; Complex sum(complex , complex); Voad main() { Complex c1,c2,c3; C1.real=3; C1.imag=4; C2.real=6; C2.imag=1; C3=sum(c1,c2); Printf(%f +i(%f)\n,c3.real,c3.imag); }

Page | 4

You might also like