Showing posts with label class. Show all posts
Showing posts with label class. Show all posts

Tuesday, March 28, 2017

C++ Part 43

Review Part VI

Parameters and Arguments
All the different terms that have to do with parameters and arguments can
be confusing. However, if you keep a few simple points in mind, you will
be able to easily handle these terms.
1. The formal parameters for a function are listed in the function declaration
and are used in the body of the function definition. A formal parameter (of
any sort) is a kind of blank or placeholder that is filled in with something
when the function is called.
2. An argument is something that is used to fill in a formal parameter. When
you write down a function call, the arguments are listed in parentheses after
the function name. When the function call is executed, the arguments are
“plugged in” for the formal parameters.
3. The terms call-by-value and call-by-reference refer to the mechanism that is
used in the “plugging in” process. In the call-by-value method only the value
of the argument is used. In this call-by-value mechanism, the formal parameter is a local variable that is initialized to the value of the corresponding argument.
In the call-by-reference mechanism the argument is a variable and the entire
variable is used. In the call-by-reference mechanism, the argument variable is
substituted for the formal parameter so that any change that is made to the
formal parameter is actually made to the argument variable.

A File Has Two Names
Every input and every output file used by your program has two names.
The external file name is the real name of the file, but it is used only in
the call to the function open, which connects the file to a stream. After the
call to open, you always use the stream name as the name of the file.

Calling a Member Function
SYNTAX
Calling _Object.Member_Function_Name(Argument_List);
EXAMPLES
in_stream.open("infile.dat");
out_stream.open("outfile.dat");
out_stream.precision(2);
The meaning of the Member_Function_Name is determined by the class of
(that is, the type of) the Calling _Object.


Classes and Objects
An object is a variable that has functions associated with it. These
functions are called member functions. A class is a type whose variables
are objects. The object’s class (that is, the type of the object) determines
which member functions the object has.

The exit Statement
The exit statement is written
exit(Integer_Value);
When the exit statement is executed, the program ends immediately. Any
Integer_Value may be used, but by convention, 1 is used for a call to
exit that is caused by an error, and 0 is used in other cases. The exit
statement is a call to the function exit, which is in the library with header
file named cstdlib. Therefore, any program that uses the exit statement
must contain the following directives:
#include
using namespace std;
(These directives need not be given one immediately after the other. They
are placed in the same locations as similar directives we have seen.)

Summary of File I/O Statements
In this sample the input comes from a file with the directory name infile.dat, and the output
goes to a file with the directory name outfile.dat.
■ Place the following include directives in your program file:
#include
#include
#include
■ Choose a stream name for the input stream (for example, in_stream), and declare it to be a variable
of type ifstream. Choose a stream name for the output file (for example, out_stream), and declare
it to be of type ofstream:
using namespace std;
ifstream in_stream;
ofstream out_stream;
■ Connect each stream to a file using the member function open with the external file name as an argument.
Remember to use the member function fail to test that the call to open was successful:
in_stream.open("infile.dat");
if (in_stream.fail( ))
{
cout << "Input file opening failed.\n"; exit(1); } out_stream.open("outfile.dat"); if (out_stream.fail( )) { cout << "Output file opening failed.\n"; exit(1); } ■ Use the stream in_stream to get input from the file infile.dat just like you use cin to get input from the keyboard. For example: in_stream >> some_variable >> some_other_variable;
■ Use the stream out_stream to send output to the file outfile.dat just like you use cout to send
output to the screen. For example:
out_stream << "some_variable = " << some_variable << endl; ■ Close the streams using the function close: in_stream.close( ); out_stream.close( );

Appending to a File
If you want to append data to a file so that it goes after any existing
contents of the file, open the file as follows.
SYNTAX
Output_Stream.open(File_Name, ios::app);
EXAMPLE
ofstream outStream;
outStream.open("important.txt", ios::app);

'\n' and "\n"
'\n' and "\n" sometimes seem like the same thing. In a cout statement,
they produce the same effect, but they cannot be used interchangeably in
all situations. '\n' is a value of type char and can be stored in a variable
of type char. On the other hand, "\n" is a string that happens to be made
up of exactly one character. Thus, "\n" is not of type char and cannot be
stored in a variable of type char.



Wednesday, March 22, 2017

C++ Part 36

4. Register Storage Class

Register storage assigns a variable's storage in the CPU registers rather than primary memory. It has its lifetime and visibility same as automatic variable. The purpose of creating register variable is to increase access speed and makes program run faster. If there is no space available in register, these variables are stored in main memory and act similar to variables of automatic storage class. So only those variables which requires fast access should be made register.

Syntax of Register Storage Class Declaration

register datatype var_name1 [= value];
For example,
register int id;
register char a;

Example of Storage Class

Example 2: C++ program to create automatic, global, static and register variables.
#include<iostream>
using namespace std;

int g;    //global variable, initially holds 0

void test_function()
{
    static int s;    //static variable, initially holds 0
    register int r;    //register variable
    r=5;
    s=s+r*2;
    cout<<"Inside test_function"<<endl;
    cout<<"g = "<<g<<endl;
    cout<<"s = "<<s<<endl;
    cout<<"r = "<<r<<endl;
}

int main()
{
    int a;    //automatic variable
    g=25;
    a=17;
    test_function();
    cout<<"Inside main"<<endl;
    cout<<"a = "<<a<<endl;
    cout<<"g = "<<g<<endl;
    test_function();
    return 0;
}
In the above program, g is a global variable, s is static, r is register and a is automatic variable. We have defined two function, first is main() and another is test_function(). Since g is global variable, it can be used in both function. Variables r and s are declared inside test_function() so can only be used inside that function. However, s being static isn't destroyed until the program ends. When test_function() is called for the first time, r is initialized to 5 and the value of s is 10 which is calculated from the statement,
s=s+r*2;
After the termination of test_function(), r is destroyed but s still holds 10. When it is called second time, r is created and initialized to 5 again. Now, the value of s becomes 20 since s initially held 10. Variable a is declared inside main() and can only be used inside main().
Output
Inside test_function
g = 25
s = 10
r = 5
Inside main
a = 17
g = 25
Inside test_function
g = 25
s = 20
r = 5

5. Mutable Storage Class

In C++, a class object can be kept constant using keyword const. This doesn't allow the data members of the class object to be modified during program execution. But, there are cases when some data members of this constant object must be changed. For example, during a bank transfer, a money transaction has to be locked such that no information could be changed but even then, its state has be changed from - started to processing to completed. In those cases, we can make these variables modifiable using a mutable storage class.

Syntax for Mutable Storage Class Declaration

mutable datatype var_name1;
For example,
mutable int x;
mutable char y;

Example of Mutable Storage Class

Example 3: C++ program to create mutable variable.
#include<iostream>
using namespace std;

class test
{
    mutable int a;
    int b;
    public:
        test(int x,int y)
        {
            a=x;
            b=y;
        }
        void square_a() const
        {
            a=a*a;
        }
        void display() const
        {
            cout<<"a = "<<a<<endl;
            cout<<"b = "<<b<<endl;
        }
};

int main()
{
    const test x(2,3);
    cout<<"Initial value"<<endl;
    x.display();
    x.square_a();
    cout<<"Final value"<<endl;
    x.display();
    return 0;
}
A class test is defined in the program. It consists of a mutable data member a. A constant object x of class test is created and the value of data members are initialized using user-defined constructor. Since, b is a normal data member, its value can't be changed after initialization. However a being mutable, its value can be changed which is done by invoking square_a() method. display() method is used to display the value the data members.
Output
Initial value
a = 2
b = 3
Final value
a = 4
__________________________________ 
Source: www.programtopia.net, submitted  by:Sagun Shrestha

C++ Part 35

Typical Program Organization

# include <iostream>  //Setup section used by compiler
storage class of a variable defines the lifetime and visibility of a variable.
Lifetime means the duration till which the variable remains active and visibility defines in which module of the program the variable is accessible.
There are five types of storage classes in C++.
They are:
  1. Automatic
  2. External
  3. Static
  4. Register // Next Post
  5. Mutable // Next Post
______________________________

1. Automatic Storage Class

Automatic storage class assigns a variable to its default storage type. auto keyword is used to declare automatic variables. However, if a variable is declared without any keyword inside a function, it is automatic by default.
This variable is visible only within the function it is declared and its lifetime is same as the lifetime of the function as well. Once the execution of function is finished, the variable is destroyed.

Syntax of Automatic Storage Class Declaration

datatype var_name1 [= value];
or
auto datatype var_name1 [= value];

Example of Automatic Storage Class

auto int x;
float y = 5.67;

2. External Storage Class

External storage class assigns variable a reference to a global variable declared outside the given program. extern keyword is used to declare external variables. They are visible throughout the program and its lifetime is same as the lifetime of the program where it is declared. This visible to all the functions present in the program.

Syntax of External Storage Class Declaration

extern datatype var_name1;
For example,
extern float var1;

Example of External Storage Class

Example 1: C++ program to create and use external storage.
File: sub.cpp
int test=100;  // assigning value to test

void multiply(int n)
{
    test=test*n;
}
File: main.cpp
#include<iostream>
#include "sub.cpp"  // includes the content of sub.cpp
using namespace std;

extern int test;  // declaring test

int main()
{
    cout<<test<<endl;
    multiply(5);
    cout<<test<<endl;
    return 0;
}
A variable test is declared as external in main.cpp. It is a global variable and it is assigned to 100 in sub.cpp. It can be accessed in both files. The function multiply() multiplies the value of test with the parameter passed to it while invoking it. The program performs the multiplication and changes the global variable test to 500.
Note: Run the main.cpp program
Output
100
500

3. Static Storage Class

Static storage class ensures a variable has the visibility mode of a local variable but lifetime of an external variable. It can be used only within the function where it is declared but destroyed only after the program execution has finished. When a function is called, the variable defined as static inside the function retains its previous value and operates on it. This is mostly used to save values in a recursive function.

Syntax of Static Storage Class Declaration

static datatype var_name1 [= value];
For example,
static int x = 101;
static float sum;

_________

source:  www.programtopia.net

Digital Design Part 3

4th→ assembler translates it to the machine language. 1.6 [20] <§1.6> Consider two different implementations of the same instru...