answersLogoWhite

0

📱

C++ Programming

Questions related to the C++ Computer Programming Language. This ranges all the way from K&R C to the most recent ANSI incarnations of C++, including advanced topics such as Object Oriented Design and Programming, Standard Template Library, and Exceptions. C++ has become one of the most popular languages today, and has been used to write all sort of things for nearly all of the modern operating systems and applications." It it a good compromise between speed, advanced power, and complexity.

2,546 Questions

How-to structure in c plus plus?

A structure in C++ is nearly the same as a structure in C. struct abc {

int item1;

int item2;

... etc...

} mystructure; There are several differences. Two examples are... In C++, you get automatic typedef'ing, so that (in this example) you would not have to say struct abc mysecondstructure; - you can just say abc mysecondstructure;. In C++, structures are very similar to classes. In fact, structures are classes, which is why you get automatic typedef'ing.

What is an example program in c plus plus to square a number using the concept of an inline function?

... double squareOf_Number(double Number)

{

return (Number*Number);

}

...

int main()

{

...

double Number = 0;

...

printf("Enter a number: ");

cin >> Number;

...

printf("Square of %f is %f\n", Number, squareOf_Number(Number));

...

}

Or you can include #include <math.h> and use the function pow(double a, double b) which returns a^b.

What is the difference between c plus plus and object code?

Short answer: They're the same.

Due to technical limitations, we on WikiAnswers cannot write C++ in the question field. So we must write "C plus plus." Unfortunately, we're also lazy. So we write "cpp" as an abbreviation.

Write a programm for addition of two numbers in C plus plus language?

Addition is an intrinsic operator that applies to all primitive data types, both signed and unsigned. There is no need to program it. The operands can be literal, constant or variable, hard-wired or generated from user-input, it makes no difference whatsoever.

#include<iostream>

int main()

{

std::cout<<"The sum of 1 and 2 is "<<(1+2)<<std::endl;

std::cout<<"The sum of 1.5 and 2.3 is "<<(1.5, 2.3)<<std::endl;

return(0);

}

What is Abstraction in C?

C is not an object-oriented programming language and therefore has no concept of abstract classes.

In C++, however, an abstract class is a base class that declares one or more pure-virtual functions. An abstract base class is also known as an abstract data type (ADT). Pure-virtual functions differ from virtual functions in that virtual functions are expected to be overridden (but needn't be) while a pure-virtual function must be overridden (but needn't be implemented by the ADT). Once overridden by a derived class, the function reverts to being a virtual function with respect to further derivatives. However, only classes that provide or inherit a complete implementation of the pure-virtual interface can be instantiated in their own right; those that do not are themselves abstract data types.

What is the difference between abstract class and static class?

Abstract ClassAn abstract class is an abstract data type (ADT) or abstract base class (ABC). It is a conceptual class. Unlike concrete classes which can serve as generic base classes for more specialised classes, ADTs can only be instantiated through derivation. For instance, circles, triangles and rectangles are all types of shape and all can therefore be derived from a shape base class. However you wouldn't want consumers instantiating a generic shape since it would be impossible to work with a shape without knowing what type of shape it actually was. Thus the shape class is an ideal candidate for an ADT.


An ADT is simply a base class that has one or more pure-virtual methods. A pure-virtual method is similar to a virtual method except that the ADT need not provide any implementation for that method. Even if it does provide a generic implementation, all derivatives must override that method, even if only to call the generic base class method. This ensures that all derivatives provide their own specialised implementations. A derivative that does not provide an implementation for all the pure-virtual methods it inherits becomes an ADT itself. However any implementations that it does provide can subsequently be inherited by its derivatives (those methods effectively become virtual methods rather than a pure-virtual method). Only classes that provide or inherit a complete implementation of all pure-virtual methods can physically be instantiated.

Going back to our shape class, the shape::draw() method is an ideal candidate for a pure-virtual function since it is impossible to draw a shape without knowing what type of shape it is. However, a circle class would be expected to know how to draw itself thus it can provide the specific implementation for drawing circles. Similarly, rectangles and triangles will provide their own specific implementations. This then makes it possible to store a collection of generic shapes and have them draw themselves without the need to know their actual type; as with all virtual methods, the derivatives behave according to their actual type.


Static ClassA static class is simply a class that contains nothing but static members. Like an abstract base class you cannot instantiate a static class, but because the members are static they can be accessed without the need to instantiate an object of the class. Static classes are useful in that they provide global functionality without the need to declare global variables and external functions that operate upon those variables (the variables can effectively be hidden in the class, thus limiting their exposure). They can be likened to a singleton class insofar as there can only ever be one instance of each data member. However, a static class is instantiated at compile time and exists for the entire duration of a program, whereas a singleton can normally be created and destroyed at any time. In terms of memory consumption alone, a singleton is far more efficient than a static class, which is one of the reasons static classes are often frowned upon.


Note that static classes have no need for any constructors, operators or destructors (they have no this pointer since there can never be any instances of the class), thus the compiler-generated default constructor, copy constructor, destructor and assignment operator must all be declared private. Some languages may do this automatically but in C++ (which has no concept of static classes) you must explicitly declare them as such.


While static classes do have their uses, bear in mind that the point of having a class in the first place is in order to instantiate independent objects from the class. Thus the only time you should ever use a static class is when the class data members must exist for the entire duration of the program and you want to ensure there can only ever be one instance of those members. However, for memory efficiency alone, a singleton class would be the preferred method. Moreover, if some or all of the static methods are closely associated with a generic class, then it makes more sense to encapsulate those methods as static members of that generic class rather than as a completely separate static class.

Write a c plus plus program that multiplies two matrices?

The previous two versions of the program given here were unnecessarily long and complicated. I am providing a much more simple and succinct version. I have constructed it on the basis of two 3*3 matrices. However you can easily change the order by replacing the "3"s of the program with your required order, provided the number of columns of the premultiplier is equal to the number of rows of the postmultiplier. If you want to dynamically allocate the orders of the matrices, you will have to use calloc and malloc, which I don't know as of yet!

#include

int main()

{

int i,j,l;

int matrix[3][3],matri[3][3],matr[3][3]={{0,0,0},{0,0,0},{0,0,0}};

printf("Enter 1st matrix: \n");

for (i=0;i<3;++i)

{

printf("\nEnter #%d row: ",(i+1));

for (j=0;j<3;++j)

scanf_s("%d",&matrix[i][j]);

}

printf("\n\n");

printf("Enter 2nd matrix: \n");

for (i=0;i<3;++i)

{

printf("\nEnter #%d row: ",(i+1));

for (j=0;j<3;++j)

scanf_s("%d",&matri[i][j]);

}

for (j=0;j<3;++j)

{

for (i=0;i<3;++i)

{

for (l=0;l<3;++l)

matr[i][j] = matr[i][j] + (matrix[i][l])*(matri[l][j]);

}

}

printf("The resultant matrix is:\n\n");

for (i=0;i<3;++i)

{

for (j=0;j<3;++j)

printf("%4d",matr[i][j]);

printf("\n\n");

}

return( 0 );

}

Recent changes to the above code

30/4/12:

Error: main() must return a value.

Error: matr must be initialised in declaration, not afterwards.

Warning: Variable k is unreferenced (removed).

Warning: Use of scanf is unsafe. Replaced with scanf_s

Benign: Commented code removed for clarity.

An alternate version with dynamic arrays is shown below.

#include

typedef unsigned int UINT;

// Forward declarations.

int ** CreateMatrix( UINT rows, UINT cols );

void InputMatrix( int ** Matrix, UINT rows, UINT cols, char * Title );

void PrintMatrix( int ** Matrix, UINT rows, UINT cols, char * Title );

void ReleaseMatrix( int ** Matrix, UINT rows );

int main()

{

// Initialise some variables.

UINT rows=0, comm=0, cols=0;

UINT i=0, j=0, k=0;

// 2D arrays (pointer-to-pointer-to-int).

int ** M1 = NULL;

int ** M2 = NULL;

int ** M3 = NULL;

printf("Calculate the dot products of two matrices.\n\n");

printf( "Enter the number of rows in the 1st matrix:\t");

scanf_s("%u", &rows );

printf( "Enter the number of common elements:\t\t");

scanf_s("%u", &comm );

printf( "Enter the number of columns in the 2nd matrix:\t");

scanf_s("%u", &cols );

// Allocate the 2D arrays:

M1 = CreateMatrix( rows, comm );

M2 = CreateMatrix( comm, cols );

M3 = CreateMatrix( rows, cols );

// Input values:

InputMatrix( M1, rows, comm, "Matrix 1" );

InputMatrix( M2, comm, cols, "Matrix 2" );

// Calculate the dot product.

for( i=0; i

for( j=0; j

for( k=0; k

M3[i][k] += M1[i][j] * M2[j][k];

// Report.

PrintMatrix( M1, rows, comm, "\nMatrix 1" );

PrintMatrix( M2, comm, cols, "Matrix 2" );

PrintMatrix( M3, rows, cols, "Dot Product of Matrix 1 and Matrix 2" );

printf("\n");

// Release memory.

ReleaseMatrix( M1, rows );

ReleaseMatrix( M2, comm );

ReleaseMatrix( M3, rows );

return( 0 );

}

int ** CreateMatrix( UINT rows, UINT cols )

{

UINT i = 0;

int ** Matrix = (int **) malloc(rows * sizeof( int * ));

for( i=0; i

{

Matrix[i] = (int *) malloc( cols * sizeof( int ));

memset( Matrix[i], 0, cols * sizeof( int ));

}

return( Matrix );

}

void InputMatrix( int ** Matrix, UINT rows, UINT cols, char * Title )

{

printf( "\nValues for %s:\n\n", Title );

UINT i=0, j=0;;

for( i=0; i

{

for (j=0; j

{

printf("Enter value for row %u, col %u:\t", i+1, j+1);

scanf_s("%d", &Matrix[i][j]);

}

}

}

void PrintMatrix( int ** Matrix, UINT rows, UINT cols, char * Title )

{

printf( "\n%s:\n\n", Title );

UINT i=0, j=0;

for( i=0; i

{

for (j=0; j

printf( "%4d", Matrix[i][j] );

printf("\n");

}

}

void ReleaseMatrix( int ** Matrix, UINT rows )

{

UINT i = rows;

while(i)

free( Matrix[--i] );

free( Matrix );

}

Write a program in c to sort an unsorted array using selection sort?

#include<stdio.h> #include<conio.h> int main() { char str[100],temp; int i,j; clrscr(); printf("Enter the string :"); gets(str); printf("%s in ascending order is -> ",str); for(i=0;str[i];i++) { for(j=i+1;str[j];j++) { if(str[j]<str[i]) { temp=str[j]; str[j]=str[i]; str[i]=temp; } } } printf("%s\n",str); getch(); return 0; } Output: Enter the string : syntax syntax in ascending order is -> anstxy

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.

Write a program in C language to implement the insertion and deletion operations in a circular queue?

//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.

What is oops in cpp?

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.

What is arrays of structure?

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.

How do you write a program in c plus plus that reads two integer arrays each having 10 elements and then prints the sum of the products?

#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.

Do while in c plus plus?

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.