English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Explain how c differs c++ its structure. Give examples.
With a simple structure that describes the structure of a c++ program
Explain what is a variable
Briefly describe the basic data type
Write a program that solve quadratic equation
write a c++ program that determine the principle amount of money for a period of a fixed interest

2007-03-08 17:08:15 · 4 answers · asked by josphine f 1 in Computers & Internet Programming & Design

4 answers

Dig the link

http://en.wikipedia.org/wiki/C++

2007-03-08 17:54:39 · answer #1 · answered by Rocks 2 · 0 0

c differs from c++ in its name itself
c++ is addition of something to c language
that something is classes .
so c with classes is c++.
c++ is an object oriented language where as c is a structured pgmg language.
examples : c doenst exhibit oops principles.
ie inheritance ,polymorphism and so on.
a variable is that which keeps on changing i.e, varying
ex: int a =1;
cout< o/p is 1
if
int a=1;
a+=2;
cout< o/p is 3
ie a changes during execution of a program

2007-03-08 17:56:51 · answer #2 · answered by Anonymous · 0 0

So, you got your exams early. You can find these answers in a simple c++ beginners guide.

2007-03-08 17:10:58 · answer #3 · answered by naren_sarma 2 · 0 0

C++ was developed by Bjarne Stroustrup as "A better C" (it was originally called "C with classes"). At a talk, I recall Bjarne saying that he was doing some simulation work while a student at Cambridge, and found himself wishing for a language combining the object-oriented features of Simula and the performance of C. C++ was the result. (For a little more history, and some links, see this page on the history of C++.)

C++ was one of several efforts to add OO features to the popular C language. The other prominent one was Objective C, probably best known for its use on the NeXT platform. Whereas C++ is strongly typed and focused on performance and C compatibility, Objective C is more in the style of Smalltalk. Though still active, Objective C is much less used than C++; and both have been eclipsed by Java since the late 1990s.

C++ extends the C language with objects, classes, and inheritance. Unlike Smalltalk, it supports strong typing, and unlike both Smalltalk and Java, it supports multiple inheritance. Also unlike Smalltalk and Java, it does not use garbage collection; as in C, programmers explicitly allocate and free object storage. Because of these factors (and others), C++ is more complicated than either C, Java, or Smalltalk.

This tutorial covers only a small fragment of the language, mainly through examples. It does not assume a prior knowledge of C. Some comparisons to Smalltalk are made to illustrate the differences between the languages, and there are a few references to the differences between C++ and Java.

To understand C++, it is first necessary to know a little C. Keep in mind that any C program (as long as it conforms to the ANSI standard for C) is automatically a C++ program, since C is a subset of C++. The following, from the famous Kernighan and Ritchie book, is a simple C program:

#include
main () // A very simple program
{
printf("hello, world\n");
}

The #include embeds definitions from the standard I/O library needed for the printf statement. Every C and C++ program has a main() function, which is called when the program is executed. Braces ( { } ) delineate blocks of statements, in this case the single statement making up the body of main(). This statement prints "hello, world" when the program is executed ("\n" is the code for carriage return/line feed). The semicolon terminates a statement (notice the difference from Smalltalk, where a period terminates a statement, and semicolon delineates a series of messages to the same object). The double quote is the character string delimiter in C; the comment delimiter is a double slash (//). Comments may also be delimited by bracketing them with "/*" and "*/".

Variables in C may be primitive types, such as characters and numbers:

char c = 'c'; // Character
int i = 10; // Integer
double x = 12.34 ; // Floating point number

Or they may be arrays of primitive types:

char c[] = {'c', 'h', 'a', 'r'}; // Array of characters (string)
char c[] = "char"; // Alternative way of initializing a string
int i[] = {2, 3, 5, 7}; // Array of integers

Arrays are referenced by the index of their elements, starting at zero for the first element; e.g., c[3] returns 'r'. (Note that other languages, such as Smalltalk, use 1 as the index of the first element in an array).

C variables may also be structures, containing other variables of different types. For example, the data associated with a bank savings account might be represented as:

struct savingsAccount {
int balance;
int accountNumber;
char name[30];
};

The individual variables, or members, of the structure are referenced by qualifying the structure name with the member name:

struct savingsAccount myAccount;
// Initialize the new account
myAccount.balance = 0;
myAccount.number = "1234";
myAccount.name = "Dave Collins";

In addition to main(), a program can have any number of other functions:

#include
int cube(int x) {
return x * x * x;
}
main () {
int i;
for(i = 1; i++; i < 10)
printf(i, " cubed is ", cube(i));
}

This example adds the function cube(int x), which returns x3 and is called from main(), plus a few other constructs. The expression i++ is common in C and C++ (in fact, it gives rise to the name "C++"); it means "use the value of i, then increment i by one." The entire for expression means "start with i set to 1; use i in the statement (or block of statements) after the for; increment i by 1; keep doing this until i gets to 10; then continue the program after the for."

The C if and while control structures resemble the for. Here is an example of if:

int i, j;
if (i == 0) {
j = 10;
i++;
printf(i);
}

Notice that the equality test in C is ==, and = is used for assignment. Most other operators are like those in other languages; != means "not equal."

You will frequently encounter in C programs the rather cryptic variant

if (!i) . . .

instead of

if (i == 0) . . .

This works because C does not have a boolean type; instead, it uses 0 for false, and any integer greater than zero for true. Thus !i means "i is false," which is precisely equivalent to i == 0.

C and C++, unlike Smalltalk, explicitly differentiate accessing an object directly (by value) from accessing it through a pointer (by reference). This is illustrated in the following example:

int sum1(int x, int y) {
return x + y;
}
int sum2(int *x, int *y) {
return *x + *y;
}
int result1, result2;
int i, j; int *pi, *pj;
i = j = 10;
pi = &i; pj = &j;
result1 = sum1(i, j);
result2 = sum2(pi, pj);

The variables i and j are declared as integers and set to 10. The variables pi and pj are declared as pointers to integers, and set to the addresses of i and j (int *i means "the object pointed to by i is an integer"; &i means "the address of i"). Pointer references are useful when objects are large, because passing a pointer is faster than copying the object. They are needed when objects are dynamically allocated, since their locations are not known at the time the program is compiled.

It is worth noting that the explicit use of pointers, and the programmer-controlled distinction between value and reference, were dropped in Java. Java still has the distinction, but it is handled automatically: "primitive" types (such as integers) are always accessed by value, complex types (objects and arrays) are always accessed by reference. Creation and dereferencing of pointers is handled automatically "under the covers," so the programmer is not explicitly aware of it. This is a significant simplification, which undoubtedly contributed to Java's popularity.

Pointers allow the programmer to statically compile only a pointer, then dynamically allocate storage for the creation of data structures or objects at runtime. For example:

struct savingsAccount *myAccount;
int size = sizeof(struct savingsAccount);
. . . .
// Allocate storage for the account
myAccount = (struct savingsAccount *) malloc(size);
myAccount->balance = 0;
myAccount->accountNumber = 1234;
myAccount->name = "Dave Collins";
. . . .
// Free the storage used for the account
free(myAccount);

Note that the storage gotten with malloc must be explicitly released using free. Otherwise, it will be released only when the program ends, and the program may exhaust all the available storage if large numbers of objects are created. It is also important that the storage not be freed while it is still in use. Notice also that whereas a direct structure reference uses dot notation (e.g., myAccount.balance), structure reference via a pointer uses an arrow (e.g., myAccount->balance).

The operation in the fifth line of the above example, (struct savingsAccount *), is a cast, explained below. It tells the C compiler that what is returned by malloc, which is a pointer to a block of storage, is now to be treated as a pointer to a savingsAccount structure.

Storage management in C++ is also the responsibility of the programmer; objects created using new must be released using delete, otherwise their storage will not be freed. In some cases (beyond the scope of this tutorial) the programmer must code a destructor function to free storage held by objects of a given class.

Storage management is a major source of errors in C and C++ programs. Some other languages, such as Smalltalk and Java, use garbage collection and do not permit programmers to manage storage usage explicitly. The garbage collector runs periodically, and determines whether any references exist to objects. If not, the objects are deleted and their storage is freed. C++, in order to insure that maximum performance can be attained, does not use a garbage collector. The designers of Smalltalk and Java argued that the small additional overhead is a reasonable price to pay in return for not being exposed to storage allocation and deallocation errors made by programmers.

One more feature of C that is relevant to C++ is the notion of a cast. Casting is changing the type of a object. As an example of why this might be necessary, the standard C library function sqrt(), which returns the square root of its argument, takes a floating-point double as its argument. Suppose we want the square root of an int (integer)? The cast operator (double) performs the appropriate conversion before calling sqrt():

int i;
double x, y;
i = 5;
x = (double) i;
y = sqrt(x);

Casting can be dangerous; what will be the result of this?

int i;
char name[30];
double x, y;
i = 5;
x = (double) name;
y = sqrt(x);

Hopefully a warning from the compiler, possibly a hard-to-find runtime error if the warning is ignored. There is no explicit casting in Smalltalk, though it may happen "under the covers," resulting in runtime errors if the object to be converted is the wrong type. C++ (and Java) also permit C-type casting, but provide facilities for making it safer.

C++ adds objects, classes, and inheritance to C. The equivalent of a method in C++ is a member function; this is just like an ordinary C function, except it is defined as part of a class, and has an implicit argument that is the object receiving the "message." The equivalent of a message in C++ is a member function call. Because objects in C++ can be referenced directly or through a pointer, there are two somewhat different equivalents for Smalltalk’s message sending:

SavingsAccount account;
SavingsAccount *pAccount;
int a, b;
pAccount = new SavingsAccount;
a = account.balance();
b = pAccount->balance();

The object account is allocated when the program is compiled. The pAccount declaration only allocates a pointer, and the assignment to new SavingsAccount dynamically allocates the object it points to. Direct references to object member functions use the "dot" (.), and references by pointer use the -> notation. (Java, since it has no explicit pointers, uses only the dot notation.) Note the similarity of the dot and arrow notations to what is used to access structure members in C. A C++ class can be thought of as a struct which can contain functions as well as data members.

A fragment of the C++ class and member function definitions for bank accounts look like this:

class BankAccount {
private:
int balance;
char* name;
public:
// Set the balance and account name
void initialize(int b char* n) {
balance = b;
name = n;
}
int balance() {
return balance;
}
. . . . .
};
class SavingsAccount public: BankAccount {
private:
float interestRate;
public:
virtual void postInterest() {
balance = balance + balance*interestRate; }
. . . . .
};

BankAccount is called a base class, and SavingsAccount is a derived class. Unlike Smalltalk, C++ differentiates between public and private members. Data members (equivalent to instance variables) and member functions can be public, accessible to any other object, or private, accessible only to member functions in the class in which they are defined. Members can also be protected, accessible to the class and its derived classes. One other thing to notice in this example is the void keyword, indicating that a function does not return anything.

The C++ analogue to BankAccount>>balance in Smalltalk is BankAccount::balance(). In C++ :: is an important part of the language (the scoping operator), and is used frequently when the code for a member function is placed outside the class definition.

The initialize() function in the example is not typical. C++ classes use constructor functions that are invoked when an object of the class is created. Constructors can take arguments, and are the normal ways of initializing objects. In this case, we might define the constructor as:

SavingsAccount::SavingsAccount(int b char* n)
: balance(b) name(n) { }

This constructor is used in the second line of the next axample below.

Though C++ objects are strongly typed, it uses a limited form of dynamic binding. We can have

BankAccount *pAccount; int b1, b2;
pAccount = new SavingsAccount(1000, "Dave Collins");
b1 = pAccount->balance();
delete pAccount; // Delete old object
pAccount = new CheckingAccount(2000, "Dave Collins");
b2 = pAccount->balance();

The compiler can guarantee that balance() is a valid function call, since it is implemented in BankAccount and pAccount points to an object of some class derived from BankAccount. The delete call here is necessary to free the storage for the first account before it is disconnected from its pointer.

C++ provides an additional form of dynamic binding, using the dynamic_cast<>() operator. A full discussion is beyond the scope of this tutorial, but basically it handles situations where we are not sure (at runtime) what the type of some object will be. To find out whether, say, an object is an instance of SavingsAccount, we can say

BankAccount * pAccount;
SavingsAccount * pSavingsAccount;
if ((pSavingsAccount = dynamic_cast<*SavingsAcount>(pAccount)) != NULL)
. . . .

The content of the if statement will be executed only if the dynamic cast returns a non-null pointer, i.e., only if the object pointed to by pAccount is something that can safely be used as a SavingsAcount.

The dynamic_cast<>() operator is one of many examples in C++ where the complexity of the language has been increased in order to simultaneously satisfy all of its goals:

*

100% backward compatibility with ANSI standard C
*

Performance equal to C
*

Strong type safety
*

Support for object orientation

Many would argue that the complexity of C++ is too high a price to pay. Based on market acceptance, it appears that for most programmers, Java is "the better C". By giving up a little performance, and some of the more error-prone features of C (such as pointers and explicit storage management), Java provides object-orientation and a C-like syntax without the complexity of C++. Many Smalltalk programmers, of course, would argue that even Java is too complex, and that giving up strong typing produces such a radical simplification that the loss of compiler detection of type errors is justified.

For a comparison of corresponding terms and concepts in in Smalltalk, C++, and Java, and pointers to information about other OOPLs, see the OOPL comparison chart.

2007-03-08 20:14:53 · answer #4 · answered by smart_shailendra 2 · 0 0

fedest.com, questions and answers