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

What is a class in c plus plus how does it compare with structure in c?

A struct in C is a POD (plain old data) type. A class in C++ can also be a POD for backward compatibility with C code, but more typically combines data with methods that operate upon the data, including constructors and initialisers.

Classes in C++ can be declared using either the struct or class keyword. By convention you will typically use struct to define POD data types and class to define more complex data types.

The only practical difference between a struct and a class is that classes use private access and inheritance by default while struct uses public access and inheritance by default. Thus the following two class definitions are functionally the same:

struct A {

A():m_data(0) {} // public access by default

private:

int m_data;

};

class B {

int m_data; // private access by default

public:

B():m_data(0) {}

};

What is a valid c plus plus identifier?

In C++ we provide names for the entities we create, the variables, functions and types in our programs. These names, or identifiers, are required to conform to some simple rules.


An identifier must start with a letter and is comprised of a sequence of letters and digits. Somewhat surprisingly, in this context the underscore _ is considered to be a letter (although there are conditions associated with its use). There's no restriction on the length of an identifier.

How is Java different than any other OOP language lke C plus plus?

There are many differences between Java and other programs, as there are also similarities: - managed code: java does not produce native code, but some byte code that will make it runnable in something called "virtual machine". The best thing about that: compile on windows and deploy that application on UNIX. - full object oriented -- even more than C++ where global variables are possible. Here, in java, everything must take place in an object - works on many operating systems. - a lot of technologies grouped in J2EE, that covers many the aspects of enterprise programming - servlets, jsp, ejb, jdbc to access the database, etc. The list is huge, I don't want to get in too much detail about that.

I guess it features some of the most mature technologies on the market.

Answer to: which programming language is more robust C sharp or Java?While I generally prefer "C" as a more robust language, I also consider anything that is released by Microsoft to be unreliable and likely to fail. Java is the product of Sun Microsystems, and has a very good reputation. While I'm not a Java programmer, I have heard nothing but good reports about Java. Answer to: why is Java more secure than other languagesJava is considered more secure than other languages for several reasons:
  • The Java compiler catches more compile-time errors; other languages (like C++) will compile programs that produce unpredictable results.
  • Java does not allocate direct pointers to memory. This makes it impossible to accidentally reference memory that belongs to other programs or the kernel.
  • ... (can't think of anything else off the top of my head)
Answer to: what is the difference between .net javaThe Major Difference between .Net and Java is

1)Java is a purely Platform independent means the application that will work in any kind of Operating System.But .Net is platform independt software.

2).Net support to develop application in different languages and to develop application Rapidly. This feature is not exist in Java

Answer to why is Java more popular than CA long time ago, many people believed Java was slower than C because Java had to run through a virtual machine. Today however, Time and speed aren't really affected by the programming language or the used technology as much as affected by memory cards capacity and processors speed (Clock rate). Hench programmers and developers started looking for the most powerful yet easy to 'learn and work with' programming language. And there came Java with the multi-platform support, Object oriented methodology and other great capabilities and features.

On the other hand, General Purpose applications are still developed using C++ because it doesn't need any intermediate software to run.

and i think that java it's been improved everyday by the newest releases of the implementation of the virtual machine.

What is the virtual keyword used for in C plus plus?

Virtual functions (or virtual methods as they are also known), are methods declared in a class that are expected to be overridden by a derived class. That is, the method is a generic method that applies to the class in which it is declared (the base class), but that may require modification by a more-specialised class (the derived class). When you implicitly call the base class method, the overridden method is called instead, thus ensure the correct behaviour. The overridden can still call the base class method explicitly, as can any other code that has access to the base class method.

If you do not declare generic methods to be virtual, overriding those methods in the derived class may have unexpected side-effects, particularly if the method is overloaded in the base class. For instance, a derived class' override will effectively hide all the overloads of the base class.

Note that if you declare any virtual function, then you are essentially notifying the end-user that the class is intended to act as a generic class and may be derived from, if required. However, if the function is declared pure-virtual, you are notifying the end-user that the class is abstract and mustbe derived from (it is not optional).

Also, if there are any virtual methods then the destructor must be virtual as well, to ensure the derived object is destroyed before the base class is destroyed.

It is often good practice to declare all methods as virtual if there's at least one virtual method, however this only applies to methods that would require alternative handling by more-specialised classes. If the base class can provide a complete implementation that requires no further specialisation, it needn't be declared virtual.

Although there is a memory cost involved in declaring virtual methods, the bulk of that cost is paid with the first virtual function which establishes the virtual table (v-table). Thereafter, the cost is minimal. The v-table ensures the most-derived method is called, thus ensuring correct behaviour of derived classes, even when working with the generic base class.

How you can access data member inside the main program in c plus plus programming language?

Public, protected and private accessors only apply to code outside of the class. Instances of a class (objects) have complete and unrestricted access to all their own instance variables (data members). They also have unrestricted access to the instance members of all other instances of the same class whenever those instances are passed as arguments to a class member method. Static methods of the class have the same privilege, as do friends of the class.

So the question isn't why an object can access its own public members without using an operator or member function. Any code outside of the class has that exact same right, but if an object has unrestricted access to its protected and private members, why should its public members be treated any differently?

How does C compiler work?

C is a programming language.

Compiler is used to convert our source code which is in high-level language or human understandable code into machine language. Compiled source code can be executed any where once if it is compiled .

Meaning c plus plus pointer to an array and pointer to a structure?

They both mean the same thing; an array is a type of data structure (a linear structure). A pointer variable is just a variable like any other, but one that is used to specifically store a memory address. That memory address may contain a primitive data type, an array or other data structure, an object or a function. The type of the pointer determines how the data being pointed at is to be treated. Pointers must always be initialised before they are accessed, and those that are not specifically pointing at any reference should always be zeroed or nullified with the NULL value. This ensures that any non-NULL pointer is pointing at something valid. Remember that pointer variables are no different to any other variable insofar as they occupy memory of their own, and can therefore point to other pointer variables.

Write a program to count the number of characters words and lines in given text c plus plus?

#include<iostream>

#include<fstream>

int main()

{

std::ifstream infile ("example.txt", std::ios::in);

unsigned chars(0);

unsigned words(0);

unsigned lines(0);

std::string delim("\t\n ");

char ch(0);

char last(0);

if (!infile.good())

{

std::cerr << "The filename is invalid." << std::endl;

return -1;

}

while (infile.get(ch))

{

switch (ch)

{

case ('\n'):

++lines;

case (' '):

case ('\t'):

// only count words if the last char was not a word delimiter

if (delim.find(last) == std::string::npos)

++words;

default:

++chars;

}

last = ch;

}

infile.close();

std::cout << "Number of chars:\t" << chars << std::endl;

std::cout << "Number of words:\t" << words << std::endl;

std::cout << "Number of lines:\t" << lines<< std::endl;

}

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.