Notes for computer science C++

 

 

 

Notes for computer science C++

 

The following texts are the property of their respective authors and we thank them for giving us the opportunity to share for free to students, teachers and users of the Web their texts will used only for illustrative educational and scientific purposes only.

 

All the information in our site are given for nonprofit educational purposes

The information of medicine and health contained in the site are of a general nature and purpose which is purely informative and for this reason may not replace in any case, the council of a doctor or a qualified entity legally to the profession.

 

 

Notes for computer science C++

 

Q.1 What is object oriented programming (OOPS)

Ans. OOPS enables you to model more closely whatever real world problem the program is being written to solve. Finally if your objects are thoughtfully designed, you can reuse more of your code than with procedural programming (modular/structured programming)

 

Q.2 What are the characteristics of OOPS.

Ans.

1.Objects: OOPS combines data to its function in a way that access to the data is allowed only through its associated function. Such combination of code and data is called an object.

2. Classes: A class in OOP is a template for object. A class is a specification of the data and the function to be encapsulated with data.

  1. Abstraction: Abstraction refers to the representation of only the essential features. This process does not include the background details and explanations.
  2. Encapsulation: Wrapping up of data and function which operate on the data into a single unit called Encapsulation.. This prevents free access to the data within a object.
  3. Inheritance: is the capacity of one class to inherit capabilities or properties from another class .The class ,whose properties are inherited is called base class or super class and the class that inherits  these properties, is called derived class or sub class.
  4. Modularity: is a property of a system that has been decomposed into a set of cohesive and loosely coupled modules.
  5. Polymorphism: is the ability for a message or data to be processed in more than one form. Polymorphism is implemented through function overloading & operators overloading .
  6. C++ Tokens: In C++, a token is the smallest individual unit in a program. For example if we say char var = ‘a’. it declares var to be a character variable which stores a character ‘a’ to it.Here char, var, ‘=’, ‘a’ and semi colon (;) all are tokens. C++ has the following tokens.
      1. Keyword:-Words with special meaning to computer.
      2. Constants:- Data items that never change their value.
      3. Identifiers:  Variables which stores data (memory address)
      4. Operators: Operators on data
        1. arithmetic +,-,/,*,%
        2. Stream extraction (>>)- set from  and insertion (<<) put to.
        3. (Relational >,<, <=, >=, = =, !=)
        4. (Logical &&, || ,!)
        5. (Increment and  decrement ( ++, --)
        6. (Conditional ?: Ternary operator)
        7. Punctuation (, ; : (  ,),{ ,} etc. )
        8. Pointer manipulation (*, &, [ ])

Basic  data type: - int(2), float(4), double(8), char(1),long double(10)

Data type modifiers:- Basic data types may have various modifiers preceding them. Signed, unsigned, long, short  to character and integer base types.

Derived data types: The following are the derived data types

  1. Array: - Can store more than one element of same type. They can be one, two or much dimensional.
  2. Function: Sub-programs are called functions.
  3. Pointers:  is a variable which holds the memory address of another variable.
  4. Reference: is an another name for a variable. It provides an alias for a previously defined variable.  Eg. Int total = 7 int & sum = total;

Here sum is declared as a reference.

Both sum and total represents same variable.

User Defined Data Types

  1. Class: represents a group of similar objects. Every object belongs to some class it describes all the properties of data type and an object is an entity created according to that description.
  2. Structure: It can store different data types. It is a collection of variables of different data types.
  3. Enumeration: - Allows us to create new types of data which are, essentially stored an integer number but which may improve your source code eligibility a small group of related objects may be put in a set and given a name.

 

The Statements in C++

    1. Declaration statement: It declares a variable of different types eg. Int a.
    2. Assignment statement:  It assigns a value eg. A=10
    3. Input/output statements: cin>>var; cout<<var; (It accepts/reads the data from user and prints/writes to file/monitor.)
    4. Control Statement: A program consists of series statements. The sequence in which these are executed may be determined during the run time depending upon some intermediate result. Control statement determine if the control is to be transferred to any statement other than one following the current one if, else – if, while, do-while, and for are control statement.

Use of I/O Operations: In C++ input/output devices are treated as files; files are treated as a sequence of stream of bytes. Streams used for input/output are

      1. cin (console input)
      2. cout(console output)
      3. cerr (standard error stream)

 

Cascading of I/O Operators: If multiple insertion (or put to) operators are used within the same line of output statement, this is known as cascading of output operators. eg. cout<<a<<b<<c++<<d; similarly, if multiple extraction (get from) operators are used  within the same line of input statement, this is known as cascading of input operators eg. cin>>a>>b; The extraction operator ignores all white space between two consecutive input values.

 

Type Conversion: The process in which one predefined type of expression is converted into another type is called type conversion.

  1. Implicit (automatic): is performed automatically by the computer. Data types  can be mixed in such expression. All operands are converted into the type of the largest operand. This process is called Type promotion.
  2. Explicit (Type casting): C++ provides a type casting facility using which data of a particular type can be converted into another type. Syntax for type casting is (type) expression.
  3. Type compatibility: In an assignment statements variables of one type can be used with variables of another type applying the rules of type conversion. The type on the right side of an assignment statement is converted into the type on the left.

 

Escape Sequences: An escape sequence is a combination of a character and a code extension character eg. ‘\n’ These are normally used to control printed output.

 

Functions (Sub-program) (Named unit of a group of statements): A function is essentially a group of statements grouped together and given a definite name. The statements in a function are delimited with {} indicates start and end of function. Function has 3 parts.

 

  1. Function prototype: Declaration of function that tells the program about the type of values returned by the function and number & type of each argument (elements)
  2. Function call: Invoke a function from another function by using its name. The function name must be followed by a set of actual parameters enclosed I in parentheses separated by coma.
  3. Function Body- Function definition: Which defines the task performed by the function.
  4. Default arguments: C++ allows us to assign default values  to a function parameter, which is useful in case, a matching argument is not passed in the function call statement. The default values are specified at the time of function declaration. E.g int sum(int a = 5, int b = 7); Any argument cannot have a default value unless all arguments appearing on its right have their default values.

 

Constant argument: It is meant that the function cannot modify these arguments. In order to make an argument constant to a function, we can use the keyword const. Eg. int sum (const int a, int b) The qualifier const  tells the compiler that the function should not modify the argument. The constant arguments are useful when functions are called by reference. The function that receives parameters can be called in one of the following ways.

  1. Call by value:- The parameters that appear in a function call statement are actual parameters. And the parameters that appears in function definition are formal parameters. The call by value method copies the value of the actual parameters into the formal parameters, that is the function creates its own copy of argument values and then use them. The original copy of the argument value remains intact.
  2. Call by reference: If the changes made in the formal parameters are to be reflected back to their corresponding actual parameters then it should use call by reference method of parameter passing. This technique passes the addresses or  references of the actual parameters to the called function. Thus the actual and formal parameters share the same memory locations. This is achieved by applying an address operators (&) to the formal parameters in the function definition.
  3. Calling functions with arrays: When an array is used as an argument to a function only the base address of the array [name of the array]is passed, not a copy of the entire array. The array name( actually a pointer to the first element in the array )is passed into the function.
  4. Call a function with pointer argument:(call by pointers) when the pointers are passed to the function, the addresses of actual argument in the calling function are copied into formal arguments of the called function. This means that using the formal arguments (the address of the original values) in the called function, we can make changes in the actual arguments of the calling function. Therefore, the called function does not create own copy of the original values, rather, it refers to the original values by the address it receives.

 

Function Returns a value  which can be int ,char ,float ,double etc(It can return a pointer also).

 

  1. Functions returning by reference: A function  may also return a reference i.e.: an alias, consider the following function.

int & max (int & a, int & b)

{ if (a>b)

return a;

else

return b;

}

 

The return type above function is int & ie the function returns a reference to int type of variable. The above function returns reference to either a or b. It does not return any  value

 

void main ()

{ int x = 5, y = 3, z = 15;

max (x, y) = z;

cout << x<< y<<z;            //output-15,3,15

z = max (x,y);

cout << x << y << z ;          //output  5,3,5

}

 

so call for max function  can be kept either side of assignment operator.

 

  1. Function returning pointers:- Function declaration must include the return type

Type *function – name (argument list)

           

            Recursion: A function call itself is called recursion.

 

 

Variable Scope:

The program parts in which a particular piece of code or a data value (eg) variable can be accessed is known as variable scope.

Storage class specifiers and variables

The storage class specifiers tells the computer how to store the subsequent variable. The storage specifiers proceeds the  rest of the variable declaration. Storage specifiers type var-name; 4 storage specifiers in C++.

 

  1. Auto: refers to automatic variable. By default, variable in a function are auto unless specified otherwise auto variable is alive as long as the function (that defines it) is executing. It can be accessed only from their parent function.
  2. Register: Variables has all the characteristics of an auto variable. The only difference between the two is that register variables provide fast access as they are stored inside the CPU register rather then in memory. It can be applied only to local variables.
  3. Extern: The extern specifier tells the computer that the variable type and names that follow it  have been declared elsewhere, so that, fresh memory is not allocated to these variables. They holds the value throughout program. Scope of the variable is the file scope where their declaration (with or without  extern) appears.
  4. Static: There can be static local and global variables, when a global variable is declared static, it means that this variable is globally available for the very file it appears in. From all other files it is hidden. Local variables are initialized  only when very first call to the function occurs. It is not destroyed when function terminates, rather it holds the value. Scope is of a local variable but the life time a global variable.

 

Static function: If the keyword static appears before any function declaration, it means that the function will now have a file scope. This function is not known outside its own file another file can use the same name for a different function. It spreads only in the file it is defined.

 

Extern function: is similar to an extern variable. The extern keyword before  a function prototype indicates that this function has been defined in another file. It is used for programs that are spread across multiple files.

 

Statements: are the instruction given to the computer. It is smallest executable unit within C++ program.

 

Compound Statement: is a sequence of statements enclosed by a pair of braces {}.

 

Conditional Control/decision statement/section statements – Normally statement are executed top to bottom. If the operational flow of control has to be altered, then selection statement is used.

2 Type of section Statements: if (single condition) and switch (multiple) in certain cases, conditional operator?: can be used as alternative to if statement.

 

 Iteration Statement: allows a set of instructions to be performed repeatedly until a certain condition is fulfilled. It is also called as looking statement. C++ provides for loop, while loop and do ….. while loop.

 

Jumping statement: Unconditionally transfer program control within a function: C++ has four statement

    1. return
    2. Goto
    3. Break
    4. Continue

 

Stdio.h

String.h

Math.h

Stdlib.h

ctype.h

getc, gets

get, putc, putchar, putw, getw     , remove, rename, fflush, fopen, fclose, remind, fread, fscanf, fseek, ftell, fwrite

strten  , strlwr, strupr, strcpy, strcat, strchr, strcmp, strcmpi

abs, pow10

sqrt, log10, tan, tanh, frexp, atan, ceil, cabs, cos, exp, floor, log, poly, pow, sin

exit, atoi, atol, atof, free,itoa , qsort, randomize, rand, div

tolower, toupper, isalnum, isascii, isdigit, iscntrl, isgraph, islower, ispunct, isupper, toascii, tolower, toupper

 

 

 

 

Classes and Objects

 

Q.1 What do you understand by a class in C++?

Ans. A Class is a group of similar objects. A class is a way to bind the data  describing an entity and its associated functions together. In C++, class makes a data type that is used to create objects of this type.

 

Q.2 Differentiate between protected and private members?

Ans. The protected and private members are hidden from the outside world of class i.e. both cannot be accessed by non-member and non-friend functions. However, the difference is that private members are not inherited by the derived class where as protected members are inherited by the derived class.

 

Q.3 What do you understand by nested class?

Ans. When a class definition contain definition of another class, this is called as nesting. The outer class is known as enclosing class and the inner class is known as nested class.

 

Q.4 What is a friend function?

Ans. A friend function is a non-member function that is granted permission to access to a class’s private and protected members.

 

Q.5 What is the significance  of :: (Scope resolution operator)?

Ans. This operator uncovers a hidden global item.

 

Q.6 Differentiate between data hiding and encapsulation.

Ans. Data hiding is a property that enforces that only relevant information is exposed to the user and rest of the information remains hidden from the user. Encapsulation is way to implement data hiding by wrapping up data and associated functions into a single unit class. The class groups its members (Data and functions) into 3 sections: private, public and protected where private and protected members remain hidden from outside world and thereby supports data binding.

 

 

Q7. What is an inline function?

Functions defined in a class specification are automatically inline. It is a hint to compiler to insert the code for the body of the function at the place where it is called, thereby saving the overheads(time spent in loading and unloading of the called function)of a function call. Inline functions ,if it is defined outside class starts with ‘inline’keyword (explicitly made inline).

 

Q.8 How member functions are defined? 

Defined outside class, the name of function must be full name(i.e class name scope resolution and the function name).

 Defined inside class, which  are automatically treated as in line function.

 

Q. 9 When will you make a function in line? Why?

When (1) Function is small (2) A function does not contain a loop, or a switch or a goto statement (3) Function does not contain static variables (4) Function is not recursive.

Why? The inline function run a little faster than the normal functions as function-calling overheads are saved but memory occupied is more.

 

Q.10 How does a class enforce data binding, abstraction and encapsulation?

A class binds together  data and its associated functions under one unit there by enforcing encapsulation means wrapping up data and associated functions together into single unit.

A class groups its members into 3 sections: Private, Protected and public. The private and protected members remains hidden from outside world. Thus through private and protected members, a class enforces data hiding.

 

Data abstraction means representation of essential features without including the background details or explanation. The outside world is given only the essential and necessary information through public members, rest of the things hidden, which is nothing but abstraction.

 

Q. What is the significance of a access labels in a class?

A class provides 3 access labels namely private, public and protected. The members declared as private and protected remains hidden from outside world and it can only be accessed by the members functions and friend function of the class.

 

Q. What are the advantages and disadvantages of inline functions?

The main advantage is that they save on the overheads of a function call as the function is not invoked, rather its code is replaced in the program. The major disadvantage of inline function is that with more function calls, more memory is wasted as for every call, the same function code is inserted in the program.

 

Q.Write short notes on significance of friend function.

Sometimes, private and protected members of a class need to be shared with an outsider function. In such case, instead of making the private and protected data public, access to these data is allowed by declaring the outsider function as a friend function. Thus still the data privacy is maintained from the outside world, only access is permitted to friend functions.

 

Q. How is working of a member function different from a friend function and non-member functions?

a) Member and friend functions have full access privilege to both  the public and private members of the class while, in general, nonmember functions have access only to the public members of the class.

b) Members function are defined within the class scope that is they are not visible outside the scope of class. Friend and nonmember functions are also visible outside the scope of class.

 

Q What is the relationship of a class and its objects? How is memory allocated to a class and its objects?

A class represents a group of similar objects. An object in an instance of the class. In C++, Class makes a data type using which its objects can be created. When a class is defined memory is allocated for its member functions and they are stored in the memory. When an object is created, separate memory space is allocated for its data members. All objects work with one copy of member functions shared by all.

 

Q. Discuss the various situation when a copy construction is automatically invoked

  1. When an object is defined and initialized with another object of the same type (to copy the data from one object to another)
  2. When an object is passed by value to a function, then the copy of the passed object is created for the function by invoking the copy constructors
  3. When a function returns an object, the copy constructor creates a temporary object to hold the return value of the function returning an object.

 

Q. What is a copy constructor? What do you understand by constructor overloading?

Copy constructor is a constructor that defines and initializes an object with another object. It takes the form classname. Constructor overloading refers to a class having multiple constructor definition, each having a different signature.

 

Stdio.h

String.h

Math.h

Stdlib.h

ctype.h

getc, gets

get, putc, putchar, putw, getw     , remove, rename, fflush, fopen, fclose, remind, fread, fscanf, fseek, ftell, fwrite

strten  , strlwr, strupr, strcpy, strcat, strchr, strcmp, strcmpi

abs, pow10

sqrt, log10, tan, tanh, frexp, atan, ceil, cabs, cos, exp, floor, log, poly, pow, sin

exit, atoi, atol, atof, free,itoa , qsort, randomize, rand, div

tolower, toupper, isalnum, isascii, isdigit, iscntrl, isgraph, islower, ispunct, isupper, toascii, tolower, toupper

 

 

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

 

Source : http://pujamcsdwarka.wikispaces.com/file/view/general_notes.doc

Web site link: http://pujamcsdwarka.wikispaces.com/

Google key word : Notes for computer science C++ file type : doc

Author : not indicated on the source document of the above text

If you are the author of the text above and you not agree to share your knowledge for teaching, research, scholarship (for fair use as indicated in the United States copyrigh low) please send us an e-mail and we will remove your text quickly.

 

Notes for computer science C++

 

If you want to quickly find the pages about a particular topic as Notes for computer science C++ use the following search engine:

 

 

Notes for computer science C++

 

Please visit our home page

 

Larapedia.com Terms of service and privacy page

 

 

 

Notes for computer science C++