Why is c plus plus a super set of c language?
C++ is a superset of C (rather than a subset of C) because it inherits directly from C and adds object-oriented programming principals to the C language. If it were a subset of C then it would reduce the language, not enhance it. Indeed, the original C++ compiler simply translated the C++ source code into C source code which was then compiled by the C compiler. Modern C++ compilers do the same sort of thing but they do it far more efficiently, without the need to produce any intermediate C source code.
//posted by Mr. VINOD KUMAR HOODA from HISAR, HARYANA
#include<stdio.h>
#include<conio.h>
void insert(int);
int delet(int);
void display(void);
void run(void);
void checkf(int z);
void checke(void);
int size=5;
int rear=-1;
int front=-1;
int queue[5]={55,66,77};
void main()
{
front+=1;
rear+=3;
int n;
int op;
printf("current queue is:");
display();
printf("\nPress:");
printf("\n1: for insertion of an element into the queue");
printf("\n2: for deletion of an element from the queue");
printf("\n3: check for full queue");
printf("\n4: check for empty queue");
printf("\n5: for exit\n");
scanf("%d",&op);
switch(op)
{
case 1:insert(size);break;
case 2:delet(size);break;
case 3:checkf(size); break;
case 4:checke(); break;
case 5:exit(1); break;
default:printf("\nWrong operator");
}
getch();
}
void insert(int n)
{
int item;
if(front!=-1&&rear!=n)
{
printf("\nEnter the item to be inserted");
scanf("%d",&item);
queue[rear+1]=item;
}
else
{
printf("\ncan not be inserted\n");
}
display();
}
int delet(int n)
{
printf("\ndeleted from queue\n");
if(front!=-1 && front!=rear)
{ run();
display();
}
else if(front!=-1 && front==rear)
{ run();
front=front-1;
display();
}
else if(front==-1)
{ printf("\nQueue is empty"); }
}
void display(void)
{
int i;
printf("\nDisplaying Queue\n");
for(i=0;i<size;i++)
printf("%d ",queue[i]);
}
void run(void)
{ int m,temp;
for(m=front;m<=rear-1;m++)
{temp=queue[m];
queue[m]=queue[m+1];
}
for(m=rear;m<size;m++)
{ queue[m]=0; }
rear=rear-1;
}
void checkf(int z)
{ if(rear==z-1)
{ printf("Queue is Full \n");
}
else
{ printf("Queue is not Full, new values can be inserted. \n");
}
}
void checke(void)
{ if(front==-1)
{ printf("Queue is empty \n");
}
else
{ printf("Queue is not empty, new values can be deleted. \n");
}
}
In c plus plus what is Mutable keyword?
mutable keyword can only be applied to non-static and non-constant member of a class. It indicates that the corresponding data member can be modified even from the constant function. (Constant function: is a function marked with the keyword const)
For eg.
class x {
private:
mutable int query_count;
int value;
public:
int get_value() const
{
query_count++;
return value;
}
};
In the code above member query_count is marked with keyword mutable. Hence it's value can be modified from constant function get_value().
Disadvantage of inheritance in c plus plus?
The only real disadvantage to inheritance is that additional memory must be set aside for the derived class virtual table. This is essentially a table of function pointers where each entry refers to the most-derived override for each virtual function. In order to use inheritance, the least-derived base class (or classes) must declare a virtual destructor. All derived class destructors are then implicitly virtual. Any class within the hierarchy can (optionally) declare one or more virtual functions which any derivative can override with its own implementation. If any class declares a pure-virtual method, that class is automatically an abstract base class and must be overridden by a more derived class. Only classes that provide or inherit a complete implementation can be instantiated. The base class that declares a pure-virtual method can (optionally) provide an implementation but that implementation cannot be inherited, it can only be called, explicitly, by a derived class override. When we instantiate objects of a derived class, there is only one virtual table regardless of the number of objects instantiated, thus the cost is minimal (dependant upon the actual number of most-derived overrides). When referring to base classes, the same table is used, but only the portion that is visible to the base class is actually accessible to it. That is, it cannot invoke overrides for virtual functions that were declared by any of its derivatives, it can only invoke those it declared itself or that were inherited from its base classes. However, the pointers for those it knows about will always point to the most-derived override, as determined by the most-derived class in the hierarchy.
Since virtual tables are only required to enable runtime polymorphic behaviour, it would be disadvantageous to use inheritance upon a class that was not intended to be used polymorphically. That is, where you wished to create a derived class but did not wish others to derive from your class. The simplest method of doing so would be to use composition rather than inheritance, by embedding the base class instead of inheriting from it. The virtual table for the base class would still exist, of course, but would not be associated with your derived class. The derived class could declare its own virtual methods (including a virtual destructor) but that would defeat the purpose of using composition, and, in turn, would generate a second virtual table specific to your composite. However, in some cases this may be desirable because embedded objects can greatly simplify the composite interface (through delegation rather than overrides) whilst allowing your composite class to be used polymorphically. Ultimately it all comes down to what it is you are trying to achieve and what implementation details you are trying to hide.
What do you mean by dynamic initialisation of objects why do we need to do this?
koiyala athu theruncha nan athukuta search pantren. mutta payale bookka pathu padita panni. netta nampathata koranku. vera athavathu solrathukkula close pannitu illa.........................su pu ko nu solliduven.
How do you implement inheritance in c plus plus?
You implement inheritance by deriving a new class of object from an existing class of object. The existing class is known as the base class of the derived class.
Classes declared final cannot be used as bases classes and classes without a virtual destructor (or a virtual destructor override) cannot be used as polymorphic base classes.
Why is the purpose of header files in c programming?
Header files allow programmers to separate interfaces from implementations. Typically, a header file contains the declaration of a single class or a group of related classes or functions, or both. The definitions are typically placed in a corresponding source file (which must include the header), although inline functions are often defined in the header itself, while incomplete types such as template classes and template functions must always be defined in the header.
Although you could place all your code in a single file, header files make it easier to re-use common functions and classes from other programs. You can also build libraries of common classes and functions, each of which requires a header (the interface) that must be included in your source in order for your programs to be able to link to those libraries. Thus headers are an aid to modularisation and re-usability, thereby reducing the need to write duplicate code.
OOP is object-oriented programming. Objects allow you to treat data and the methods that operate upon that data as self-contained entities which can then be used by themselves, or to create new objects, either by deriving from them (inheritance), or by embedding them inside other objects. This allows highly complex data structures to be modelled more easily than with C alone, whilst retaining the mid-level programming capability of C itself.
A simple array has of basic data type such as char, int, float... arrays of structure has the type of structure.
struct student std[12];
Here std is an arrays of structure.
How do you use Scope resolution operator in c?
Scope resolution operator is resolved to unhide the scope of a global variable.
for eg:
#include<iostream.h>
int x=20; //global variable
void main()
{
int x=10; //local variable
cout<<x;
}
output will be 10 only. you will never get the answer as 20. local and global variable are having the same name(here x). so unhide the scope of the global variable you have to use a scope resolution operator(::) before the variable.
so if you are changing the above code as :cout<<::x; you will get the answer as 20.
#include<iostream>
#include<iomanip>
#include<time.h>
void print(int a[], size_t size)
{
using std::cout;
using std::endl;
using std::setw;
for(size_t index=0; index<size; ++index)
cout<<setw(5)<<a[index];
cout<<endl;
}
int main()
{
srand((unsigned)time(NULL));
const size_t size=10;
int a[size], b[size], c[size];
// Initialise a and b with random integers (range 1-99)
for(size_t index=0; index<size; ++index)
{
a[index]=rand()%99+1;
b[index]=rand()%99+1;
}
// Initialise c with products of a and b.
for(size_t index=0; index<size; ++index)
c[index]=a[index]*b[index];
// Calculate sum of c.
int sum=0;
for(size_t index=0; index<size; ++index)
sum+=c[index];
// Print results.
std::cout<<"Array a:\t"; print(a,size);
std::cout<<"Array b:\t"; print(b,size);
std::cout<<"Products:\t"; print(c,size);
std::cout<<"Sum product:\t"<<sum<<std::endl;
}
Why are pointers needed in C programming?
pointer is used when we want to retain the change in values between the function calls.
Similarly double pointer is used when we want to retain the change in pointers between the function calls. If you want to modify pointers than you need double pointer to retain the change.
How operator overloading is useful in class based programming?
The concept of Operator Overloading is similar to Method Overloading, in that the meaning of a given operator symbol changes according to the context it is being used in. That is, the semantics of the operator symbol are flexible, rather than fixed.
The idea behind Operator Overloading is to take a common symbol, and adjust it's meaning to something logical for contexts other than what it was originally restricted to.
The arithmetic operators ( + - * / ) are good examples. Using Operator Overloading, I could define that 'SomeArray + SomeValue' means that I should add SomeValue to the end of the array SomeArray.
In general, Operator Overloading is what is called 'syntactic sugar' - it makes things more readable. For instance, the equivalent way to do the above example via method calls would be: SomeArray.addToEnd(SomeValue)
The major problem with Operator Overloading is that it depends on people having the exact same interpretation of what an operator would mean in the new context, which is difficult to assure. Going back to the above example, there is some ambiguity as to where 'SomeArray + SomeValue' would mean to add in SomeValue - should SomeValue be added to the start of the array, or the end of the array? The answer is not obvious, and one would have to go look through the overload definition. While this confusion is also possible with methods, properly named methods (i.e. using addToEnd() rather than just add() ) helps avoid this entirely.
For this reason, Java does not support user-defined Operator Overloading. Java does support certain operator overloading in narrow contexts, but only those defined by the language itself. That is, the '+' sign is overloaded to allow for string concatenation. However, the designer of Java (James Gosling) decided that his preference was to avoid Operator Overloading completely due to his perception of a "clean" language.
How do you alternate between reading char and int in C plus plus from a text file?
Text files do not contain int types, only char types. Alternating between the two when reading a text file is an exercise in futility.
The assumption here is that the text file contains integers in string form. To extract the integers you must convert the digits into values. The digit '4' is not a number; four is the number, 4 is just the symbol for the number four. However, '4' is ASCII character code 52, thus if we subtract 48 we get its value. Character '0' is ASCII 48, thus subtracting '0' is the same as subtracting 48. If 0 <= value <= 9, then we know the character is a digit.
The following example demonstrates how to extract integers from strings. The code can be easily adapted to extract integers from text files.
#include <iostream>
int main()
{
char str[] = "This is a string that has 54 characters and 2 numbers.";
std::cout << "'" << str << "'\n" << std::endl;
int idx = 0;
again:
int number = 0;
while( str[idx] )
{
char value = str[idx++] - '0';
if( value >= 0 && value <= 9 )
{
number *= 10;
number += value;
}
else if( number )
break;
}
if( number )
std::cout << "The number " << number << " was found in the string." << std::endl;
if( str[idx] )
goto again;
return( 0 );
}
Output:
'This is a string that has 54 characters and 2 numbers.'
The number 54 was found in the string.
The number 2 was found in the string.
How do you calculate percentage of marks obtained in 1 subject in c plus plus?
You can't, you have to come up with variables to calculate grades
The do while loop is useful for the special loops that they must circulate at least one time.
#include <iostream>
using namespace std;
int main()
{
int num,digit;
cout<<"Enter a #\n";
cin>>num;
cout<<"Invers is : ";
do
{
digit=num/10;
cout<<digit;
num/=10;
} while(num != 0);
return 0;
}
Printout of output in c plus plus?
This question could mean one of two things: either the program should print its machine code, or it should print its source code. Printing the machine code is easy enough since the first argument passed to the program contains the executable name. So you simply need to open this file as a binary input file and redirect the content to std::cout. Some characters will be non-printable of course, so it might be better to convert every byte to its hexadecimal equivalent and print that instead.
A machine code program that prints its own source is somewhat more complex. Firstly, you need to know which file or files to print. If the source code is contained in a single source file then it's relatively simple to print the one file provided you tell the program which file to print. Using the executable file name to derive the source code file name is one possibility. And if the source has a header this could also be derived.
If the program source is spread over multiple sources with many includes then you should locate the project file that lists all the files used by the project and parse this file in order to obtain each file name you need to print. You can safely ignore standard library includes and binary library links since you'd only be interested in your own user-defined files. Ideally these will all be placed in the same folder so they'll be easy to identify. You might also have re-usable code modules in other folders but if they're all within the same folder hierarchy they should be easy to identify as well. Once you have a list of all the project files files you can go ahead and print them.
Can we use gotoxy function in C plus plus?
Ideally you would not manipulate std::cout using such a low-level function. Console output is intentionally generic so that output can be easily redirected to any output device that accepts a character stream. As such, this code will not work correctly if the user were to redirect output to a disk file or a printer, or use the output as input to another program. If you wish to format screen output in a non-generic manner, do not use the console, use a screen-specific context device instead.
#include<iostream>
#include<string>
#ifdef WIN32
#include<windows.h>
#endif WIN32
void gotoxy(int x, int y)
{
#ifdef WIN32
static HANDLE h = NULL;
if(!h)
h = GetStdHandle (STD_OUTPUT_HANDLE);
COORD c = { x, y };
SetConsoleCursorPosition (h,c);
#elif linux
printf("%c[%d;%df",0x1B,y,x);
#else
static_assert (false, "unsupported platform in gotoxy()");
#endif WIN32
}
void draw_box(unsigned x, unsigned y, unsigned width, unsigned height)
{
gotoxy (x, y);
std::cout << std::string (width, '*');
for (unsigned z=2; z<height; ++z)
{
gotoxy (x, ++y);
std::cout << "*";
gotoxy (x+width-1, y);
std::cout << "*";
}
gotoxy (x,++y);
std::cout << std::string (width, '*');
}
int main()
{
draw_box(10,10,5,4); // draw 5x4 box at {10,10}
gotoxy (0,25);
}
What are the merits and demerits of while loop and do while loop in c plus plus?
You use a while() loop when you want to test a condition before entering a loop for the first time, which may bypass the loop completely. The condition is also tested before beginning each iteration.
A do..while() loop always executes the loop at least once, and tests the condition at the end of each iteration before beginning a new iteration.
What is the difference between friend function and inheritance in c plus plus?
There is no such thing. When declaring a friend function only the explicitly-scoped friend is granted private access. The friend function may well be declared virtual within its own class but none of its overrides are granted access unless they are explicitly granted access.
How may the double variables temp weight and age be defined on one statement?
Use the comma operator:
double temp {1.0}, weight {5.5}, age {21.0};
Compare c plus plus and visual basic?
Visual Basic is a Windows-specific programming language, developed by Microsoft. C++ is a standard, generic and cross-platform programming language. Microsoft's implementation is called Visual C++, but it is not standards-compliant. Visual Basic requires a runtime library. C++ does not. Visual Basic is 100% object-oriented. C++ is not 100% object-oriented, but gives programmers greater freedom of choice. C++ is efficient, compact and performs extremely well on a wide variety of hardware. Visual Basic programs are inefficient, generally large, and much slower than equivalent C++ programs, and only run on Windows.
What does if statements in c plus plus implement?
C++ if() statements implements a comparison and a jump opcode. By way of example, consider the following code:
if( x 100 ) generates a compare and jump opcode (cmp and jne).
The cmp opcode compares the value of x with 64h (100 decimal) which will either set or clear ZF (the zero flag). If x is 100, then ZF will be unset, otherwise it will be set.
The jne (jump if not equal) opcode tests ZF. If it is set, then x was not 100 and the operand (1181934h) is passed to the PC register (the program counter). The IR (instruction register) will fetch the value from PC on the next cycle. This ultimately causes execution to jump to the statement immediately following the else clause of the if statement (the second printf statement).
If ZF is not set, then x really was 100 and the PC register remains unaffected. At that point the PC register will contain the value 0118191Bh, which is the next instruction after the if statement, thus execution simply falls through to the first printf statement. After processing the printfinstructions, execution will reach the else clause which simply forces a jump to bypass the second printfstatement.
Thus, one of the printf statements is executed and then execution continues from the instruction at 118194Bh, which is not shown but is the next instruction after the second printfstatement.
What is the purpose if declaring object with keyword const in c plus plus?
The const keyword transforms a variable into a constant. This means the constant cannot be altered via that constant's identifier. The const keyword can also be applied to a class instance method, such that the method will not alter a class instance's immutable members.
Note that the const keyword is merely a programming aid that provides assurances a constant will not be altered inadvertently. However, it is still possible to alter the constant by using a non-constant pointer to the constant. However you have to make a conscious effort to override constant behaviour.