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

Why does c plus plus have type modifiers?

There are four modifiers in C++: long, short, signed and unsigned. They are used to modify primitive types (int, char, float and double) to change their behaviour. If no type is specified, int is assumed. Thus a long long turns a 32-bit integer into a 64-bit integer while unsigned ensures an integer is always in the positive range.

When will you make a function inline and why?

Inline expansion relates to the way in which a function call is replaced with the function body in your compiled code. The idea is that by eliminating the function call, your code will be faster because you eliminate the overhead of the function call (which requires a lot of unnecessary pushing and popping from the call stack). However, if the function is large and is called many times throughout your code, the extra speed gained by eliminating the function calls might be outweighed by the performance lost due to the increased code size.

Thus you will make a function inline when you know that there will be an advantage in doing so. In reality, however, marking a function for inline expansion merely states to the compiler that inline expansion is desired but is not required. The compiler is free to ignore the request when it can find no advantage in doing so. Some compilers may provide alternative methods that allow the programmer to overrule the compiler, but these should generally be avoided unless you can be absolutely certain there is an advantage to be gained (which will require an intimate understanding of your compiler's optimisers). In most cases it is best to let the compiler decide when inline expansion should occur, because what may be suitable for one program may not be suitable for all programs.

Aside from implementation-specific methods, there are essentially two ways to mark a function as a candidate for inline expansion: implicitly and explicitly. Implicit inline expansion occurs automatically whenever you define a function within its own declaration. Explicit expansion occurs when the declaration and definition are separate, but the definition is explicitly marked inline and appears in the same translation unit as the declaration. Where there is only one .cpp file, the definition may appear in that .cpp file (the declaration should always be placed in a header), but in all other cases this would result in an "unresolved external symbol" error from the linker. Thus the definition must appear in a header.

Note that although a definition is also a declaration, for the purpose of this answer a definition provides implementation while a declaration does not (a declaration in this sense simply means a forward declaration that will be implemented elsewhere).

The problem with inline expansion (whether implicit or explicit) is that the implementation may be visible to the caller, because it must also be visible to the linker. Whether this is desirable or not depends upon the function's purpose. However, the recommended method is to use explicit inline expansion, particularly with class methods. Although you cannot hide implementations within headers, you can limit the exposure by keeping the implementation physically separate. Consumers are only interested in the interface, so there's little point in confusing them with non-essential information within the declaration, which includes the use of the inline keyword (only the definition should be explicitly marked for inline expansion).

In most cases, inline expansion should be limited to functions that contain very simple statements or expressions. These can often result in reducing code size as well as improving performance. However, the same can be said of more complex functions where the compiler's optimisers can eliminate redundant code through procedural integration (making large functions smaller). Increased code size is not necessarily a bad thing unless the application is CPU-bound and the increased code size would result in increased paging (commonly known as thrashing). For non-CPU-bound applications inline expansion is largely irrelevant because overall performance would ultimately be determined by the bottlenecks elsewhere, such as file systems, databases or networks.

What is the difference between normal function and static function in c plus plus?

When a function is declared static at file scope, this means the function has internal linkage only. That is, the function is only accessible to the translation unit in which it is declared. This applies to both C and C++. However, we can achieve the same thing in C++ by declaring a (non-static) function in an un-named (anonymous) namespace. Whether this better represents internal linkage or not is merely a matter of taste.

In C++ we can also declare static functions inside a class. Static member functions differ from non-static member functions in that they do not have access to a 'this' pointer; they are local to the class, not to objects (instances) of the class. As such, they can be invoked without having to instantiate an object from the class.

Built-in functions in C?

You can have #include after Stdio.h ...it has so many built in mathematical functions like CIRCULAR FUNCTIONS, ABSOLUTE VALUE and more..

Sadly, built-in functions and library functions are different things... there are no built-in functions in C (except for sizeof, which isn't an actual function).

A five digit no is entered through the keyboard write a program to obtain the reversed no and to determine whether the original no and reversed no is equal or not?

1) first you have to find the reverse of an integer..

code is given below,

#include<stdio.h>

void main()

{

int a,b,m,s=0;

printf("enter the value of a");

scanf("%d",&a);

b=a;

while(a!= 0)

{

m=a%10;

s=s*10+m;

a=a/10;

}

if(s == b)

{

printf("original number is equal to the reversed number");

}

else

{

printf("original number is not equal to the reversed number");

How many base class and derived class can be created in inheritance?

As many as required. The only practical limits are those imposed by the hardware. For instance, 32-bit systems can only address a maximum of 4GB, but only 2GB is actually available to applications. On 64-bit systems there is no practical limit other than hard-drive space (for the virtual memory paging file).

Remember that every class of object requires memory to store its member variables (plus padding for alignment), which has to be multiplied up by the number of instances of those classes. Thus the more complex the hierarchy, the fewer instances you can create overall. Since alignment padding can add a substantial overhead, it's best to declare member variables from largest to smallest within each class because memory is allocated in the same order the members are declared. If a v-table is required (which it typically will be in a multi-level hierarchy) this will consume additional memory: essentially one function pointer per virtual function per override.

That said, it is difficult to imagine any hierarchy so large that you will hit a memory limitation, even on a 32-bit system, unless you happen to embed a particularly large member variable in your class, such as a hi-resolution image or video, rather than use a disk-based file stream. Aside from that the main concern is in how many instances of that hierarchy can you physically construct at one time. However, you need only look at some of the hierarchies within the Microsoft Foundation Classes to realise that your probably just scratching the surface of what is actually possible.

Should I learn C or C plus plus first if I want to learn C?

Very! C++ isn't the best language out there, it certainly has its issues, but it's very powerful. It's also fairly low-level, as far as modern languages are concerned. Python has all the power with few of the costs. If you already know how to program, you should be able to pick it up in less than two hours. Most the concepts you learned in C++ (inheritance, polymorphism, etc) still apply, too. Python has the advantage of plenty of super easy-to-use libraries for many thing (such as downloading a web page). It can't hurt to try, so give Python a spin and see if it benefits you.

see related link below

Infix to postfix C?

Infix Expression :

Any expression in the standard form like "2*3-4/5" is an Infix(Inorder) expression.

Postfix Expression :

The Postfix(Postorder) form of the above expression is "23*45/-".

Infix to Postfix Conversion :

In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+. The algorithm for the conversion is as follows :

  • Scan the Infix string from left to right.
  • Initialise an empty stack.
  • If the scannned character is an operand, add it to the Postfix string. If the scanned character is an operator and if the stack is empty Push the character to stack.
    • If the scanned character is an Operand and the stack is not empty, compare the precedence of the character with the element on top of the stack (topStack). If topStack has higher precedence over the scanned character Pop the stack else Push the scanned character to stack. Repeat this step as long as stack is not empty and topStack has precedence over the character.
    Repeat this step till all the characters are scanned.
  • (After all characters are scanned, we have to add any character that the stack may have to the Postfix string.) If stack is not empty add topStack to Postfix string and Pop the stack. Repeat this step as long as stack is not empty.
  • Return the Postfix string.

Example :

Let us see how the above algorithm will be imlemented using an example.

Infix String : a+b*c-d

Initially the Stack is empty and our Postfix string has no characters. Now, the first character scanned is 'a'. 'a' is added to the Postfix string. The next character scanned is '+'. It being an operator, it is pushed to the stack.

Stack

Postfix String

Next character scanned is 'b' which will be placed in the Postfix string. Next character is '*' which is an operator. Now, the top element of the stack is '+' which has lower precedence than '*', so '*' will be pushed to the stack.

Stack

Postfix String

The next character is 'c' which is placed in the Postfix string. Next character scanned is '-'. The topmost character in the stack is '*' which has a higher precedence than '-'. Thus '*' will be popped out from the stack and added to the Postfix string. Even now the stack is not empty. Now the topmost element of the stack is '+' which has equal priority to '-'. So pop the '+' from the stack and add it to the Postfix string. The '-' will be pushed to the stack.

Stack

Postfix String

Next character is 'd' which is added to Postfix string. Now all characters have been scanned so we must pop the remaining elements from the stack and add it to the Postfix string. At this stage we have only a '-' in the stack. It is popped out and added to the Postfix string. So, after all characters are scanned, this is how the stack and Postfix string will be :

Stack

Postfix String

End result :

  • Infix String : a+b*c-d
  • Postfix String : abc*+d-

What is the merits and demerit of recursion in algorithm?

The advantages of recursion tend to revolve around the fact that there are quite a few algorithms which lend themselves to recursion (tree traversal, binary searches, quick sort, etc.)

The disadvantages of recursion include:

* finite number of recursive steps (limited heap space) * speed/efficiency (easier to increment a loop counter than call a function)

How do you write a C plus plus program to find simple interest using arguments?

#include <stdio.h>

#include <conio.h>

void main()

{

float p, r, si;

int t;

clrscr();

printf("Enter the values of p,r and t\n");

scanf ("%f %f %d", &p, &r, &t);

si = (p * r * t)/ 100.0;

printf ("Amount = Rs. %5.2f\n", p);

printf ("Rate = Rs. %5.2f%\n", r);

printf ("Time = %d years\n", t);

printf ("Simple interest = %5.2f\n", si);

}

Where the c plus plus encapsulation done?

There are no statements as such. Encapsulation is a design concept. The basic principal of encapsulation is that an object should contain all the information necessary to use the object, nothing more and nothing less. In other words, an object is a self-contained entity.

What is function overloading in oop?

An overloaded function is a function that has several implementations, the only difference being the number and type of parameters, including usage of the const keyword. Overloads cannot differ by return type alone. The following is a trivial example of function overloading.

const int & max(const int & lhs, const int & rhs){return( lhs>rhs ? lhs : rhs );}

const char & max(const char & lhs, const char & rhs){return( lhs>rhs ? lhs : rhs );}

Since the implementation is exactly the same, regardless of the type of parameters, it would make more sense to enlist the compiler to generate all the possible variants of this overloaded function using a template function. The compiler then generates all the overloads as required, and you only have one function to maintain.

Overloads are better suited to functions that have completely different signatures with a different number of parameters. For instance:

typedef struct rect_tag

{

float width;

float height;

} rect;

const float & Area( const rect & rc ){ return( rc.width * rc.height ); }

const int & Area( const int & width, const int & height ){ return( width * height ); }

const float & Area( const int & width, const float & height ){ return((float) width * height ); } const float & Area( const float & width, const int & height ){ return( width * (float) height ); }

The point of overloading functions is increased flexibility.You don't have to worry about which version of a function you call, nor is there any need to cast parameters to a specific type, since the compiler can work out which version of a function to call simply from the type of parameters you supply. If no suitable overload exists, the compiler will warn you so that you may either provide one, or explicitly cast your variables to a suitable version.

Mixing overloads with default parameter values increases the flexibility further, provided there is no ambiguity regarding which version of the overload is being called.

What is cout in c plus plus?

Answer:

Difference between "cin" & "cout" is:

"cout"

"cin"It stands for console output. Console means the computer display screen. The 'cout' is a predefined object. It is used as an output statement to display output on the computer screen. It I a part of iostream header file.

Flow of data from one location to another location is called stream .The 'cout' is the standard output stream.

The syntax of 'cout' is;

cout<< const1/vari1,.........................;

cout name of output stream object.

<< put to operator or insertion operator. It directs the output to the output device.

const1/var1, These are the constants and variables that are used to show output on the screen.

For e.g.

cout<<"one kilobyte="<<1024<<" bytes";

In above example two string constants, one numeric constant and three put to operators are used and its output will be: One kilobyte= 1024 bytes.

It stands for console input. It is an input stream. It is used as input statement to get input from the keyboard during execution of the program.

When an input statement is executed, the computer waits to receive an input from the keyboard. When the value is typed and enter key is pressed the value is assigned to the variable and control shifts to next statement.

It is also the part of iostream header file.

The syntax of 'cin' is:

cin>>var1 [>>var2...];

cin represents the object used as an input stream and gets the value from keyboard.

>> Extraction operator or get from operator. Its get an input from the input device and assigned t the variable.

var1, var2 represents list of variables and each variable I separated by '>>'

At least one variable on the right-hand-side of the ">>"operator must be used.

For e.g.

cin>>a>>b>>c;

User defined data types in c plus plus?

C++ provides the following fundamental types:

  • A Boolean type (bool)
  • Character types (char and wchar_t)
  • Integer types (int, short, long and long long)
  • Floating-point types (float, double and long double)
  • A type, void, used to signify the absence of information.

Fundamental types correspond to the basic storage units of the machine. From the fundamental types we can construct other types using declarator operators:

  • Pointer types (such as int*)
  • Array types (such as char[])
  • Reference types (such as double& and char&&)

The Boolean, character and integer types are collectively known as the integral types. The integral and floating-point types are collectively known as the arithmetic types.

The fundamental types, pointers, arrays and references are collectively known as the built-in types.

The integral types can be further modified using the signed or unsigned modifiers. Strictly speaking, both long and short are also type modifiers because a short implies a short int. This is simply an artefact from C programming where int was implied in the absence of an explicit type.

Note that aliases (using x = type) and type definitions (typedef) are not types per se, they are simply alternative names for preexisting types. For instance, although wchar_t is a built-in type because it does not require a declaration, in reality it is just an alias for an implementation-defined integral type (typically unsigned short).

From these built-in types we can construct other types:

  • Data structures and classes (such as std::vector and std::string)
  • Enumeration types (enum and enum class)

Data structures, classes and enumeration types are collectively known as user-defined types.

In essence, any type that requires an explicit declaration is a user-defined type. This includes all C++ standard library types such as std::string because we cannot use a std::string object unless we include the header where the type is declared.

Far pointer size in C plus plus?

If you are talking "far pointer", then you are probably talking about real mode in a 16 bit environment such as DOS or Windows 3.1, or in Virtual 8086 mode in Windows 95 or higher. In this mode, addressing is segmented into 65536 segments of 65536 bytes each, but each segment overlaps the next by only a 16 byte offset. This gives you addressability to 1048576 bytes. A far pointer is a 32 bit object, containing a 16 bit segment and a 16 bit offset. int __far *p; /* a far pointer called p which points to an int */

What is the first function executed in a C plus plus program?

For gcc there's a non-standard solution. Declare the function with __attribute__((constructor)) (note the double parentheses).

Like this:

void init(void) __attribute__ ((constructor));

void init(void) {

// your code goes here

}

Starting with gcc 4.3 there's even a possibility to assign a priority to the "constructor". See http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Function-Attributes.html for details.

Define protected access modifire in c plus plus?

The access privileges in c++ are

1.public

2.private

3.protected

and by default its private

Difference between Data Type and Abstract Data Type?

A data type tends to mean a primitive data type. Primitive data are built-in data types, such as integers, characters and Booleans. They are basic constructs of the language (that is, they are built into the language).

Primitive data also tends to be of a strict data type, meaning you can't treat characters like integers or Booleans like integers, etc., although some languages will support implicit casting of primitive data types (for example, will treat Booleans like integers if you use a Boolean in an arithmetic operation).

Abstract data types are generally constructed by the user or by a higher level language. For example, you might create a currency data type, which generally acts like a float but always has a precision of 2 decimal places and implements special rules about how to round off fractions of a cent.

Abstract data types also often contain the ability to either be treated as a specific type of primitive data in certain circumstances (for example, many languages allow you to treat strings as character arrays); or contain certain rules / methods to manipulate their data (such as a programming language allowing you to cast a float as an integer).

A data structure is a gathering together of many different data types. For example, objects and arrays are data structures. Data structures usually can contain information of many different types (such as strings, integers, Booleans) at the same time, and in more complex structures -- namely, classes -- can contain specific methods, properties and events to manipulate that data, change its type, etc.

What are the drawbacks of structured programming language over object oriented programming language and explain with suitable examples?

The main drawback to structured programming is that the data and the methods that operate upon that data are completely separate. This means that any code with access to the data can modify that data. In and of itself that is not a major problem, but it places the onus upon the programmer to ensure that all data is modified in a consistent and highly predictable manner, which may require additional verifications and assurances within the code to ensure that is always the case. For instance, if a variable must have a limited range of 0 to 100, then the programmer may be forced to ensure that is the case before he can use the data, and may need to perform that same check every time the data is used.

Object oriented programming combines the data and the methods that operate upon that data into a single entity, presenting the data to the outside world in a more abstract form, limiting its exposure and protecting its integrity. Mutators that modify the internal data act as gatekeepers, assuring that any and all modifications to the data are consistent. The programmer no longer needs to continually check the state of the data before using the data, as the onus is now upon the object to ensure that data integrity is maintained at all times.

By delegating the workload to the objects themselves, highly-complex data models can be created simply by embedding objects within objects, where each individual object is solely responsible for its own data integrity. The programmer can then manipulate these highly complex structures as a single entity, rather than through a series of separate functions and data that could very easily be corrupted by a single errant statement that would be difficult to trace.

Write a program to accept a character value from the user and sHow is its ASCII value?

You don't need to write a program to do this. Each character (char) is actually an int. If you want to see the ASCII value of a char you can simply:

char c = 'a';

System.out.print( (int)c );

C plus plus program to find factorial of given number using function overloading?

Use this function: long factorial(int N)

{

if (N == 0)

{

return 1;

}

else

{

return N*factorial(N-1);

}

}

Fibonacci c plus plus program?

#include<iostream>

int main()

{

int x=0, y=1;

std::cout<<x<<" ";

std::cout<<y<<" ";

while( y<1000000 )

{

std::cout<<(y+=x)<<" ";

x=y-x;

}

std::cout<<std::endl;

return(0);

}

Need of friend function in c plus plus?

Declaring a function to be a friend of a class allows the friend function to gain private (and protected) access to that class, just as it would if it were declared a static member function of the class. Most of the time you will want to use static functions rather than friend functions, but sometimes it is necessary for a member method of another class or an external function to be permitted private access. Although some will tell you this undermines the encapsulation of the class, it does not. If anything, it reinforces that encapsulation, by only allowing the specified function to gain private access. Although the friend function is not physically a member of the class, it automatically becomes tightly bound to the class. That is not necessarily a bad thing when you're only dealing with a limited number of friends, but a class that has many friends can often be an indication of poor class design. Thus it is important to limit friendship and to only use it when it is absolutely required, whenever possible.

By way of an example, suppose you have designed a parent and child class. Even without friend functions, the two are implicitly bound to each other: the parent object is a container for child objects, while child objects refer to their parents. All work is delegated and coordinated between the two classes accordingly; they work together as one. Most of the work can be encapsulated without the need to explicitly bind the classes together, however child objects typically refer to their parent object (via a member pointer) and might also be permitted to change their parent, but we wouldn't want to expose that pointer outside of the class, nor would we want to expose any mutators such as child::set_parent() outside of the class. But since the two classes are imlicitly bound to each other, we can declare specific methods of the parent class to be friends of the child class, such as parent::add_child(). In this way we can be sure that whenever we add a child to a parent, the parent not only attaches the child to itself, but also detaches the child from any existing parent beforehand. Far from undermining the encapsulation, this friendship reinforces it, assuring us that both classes are tightly bound.

Need of function overloading in c plus plus?

The need for function overloading is to allow the same function call to accept different parameter types and/or a different number of parameters. The function signature differentiates the functions. The return type is also part of the signature, and needn't be the same for every overload.

Where the function signature is largely the same, with the same count of parameters but a different parameter type and return type, template functions can provide an alternative method of creating the function overloads. The compiler generates the necessary code for you, on an as-required basis, so you only need to write the function once, rather than once for each type.

Explain types of inheritance in c plus plus?

There are essentially just two types of inheritance: single inheritance and multiple inheritance. Single inheritance simply means that one class derives directly from another class. Multiple inheritance means one class is directly derived from two or more classes.

However, since base classes can (and often are) be derived from other base classes, you can think of this type of inheritance as being multi-level. In addition, two or more base classes that share a common base class can use virtual inheritance. What this means is that the common base class becomes a direct base class of the most-derived class, and this one instance is shared, virtually, by all the base classes that would otherwise inherit directly from it. in other words, there is only one instance of the common base class, rather than one instance per class that inherits from it. This is useful in the so-called "dreaded diamond" formation, where a derived class inherits from two base classes, both of which inherit from a common base class.

Trending Questions
What is a delegate in C plus plus? Is Recursion operation of the stack? What do you mean by OOps? Why does an abstract class often define methods WITHOUT actually implementing them? Is C plus plus same as Microsoft Visual C plus plus Express Edition? Write a c plus plus program to find the largest and second largest number from an array? What is the output of the following program int total int sum equals total total equals 100 print sum equals percent d total equals percent d sum total? If the total selling price of 15 items and the total profit earned on them is inputed through the keyboard write a program on C plus plus to find the cost price of one item help would be great? What are applications of pre-increment and post-increment operators why these operators behaviour are made like this is there any reason for such behaviour? Difference between function overloading and default arguments? Is the ccc plus language for programming? Which operand should be passed in the binary overloaded operator function as a second operand? How does member function of class define? Write a program in c to print a mark sheet? What were the aimsobjectives of the CPP? C plus plus Program that will convert from decimal to octal? What is the difference between header files and namespace in cpp? C plus plus program to generate Fibonacci series? Flowchart of find the difference sum product and average of A and B Print the result? C plus plus prog a function sum that returns the sum of all Values in the given array int sum int list int arraySize?