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

Functions used for manipulation of file pointer?

Functions_used_for_manipulation_of_file_pointers_are_as_follows:">Functions used for manipulation of file pointers are as follows:

seekg():_Moves_get_pointer_(input)_to_a_specified_location.">seekg():Moves get pointer (input) to a specified location.

seekp():_Moves_put_pointer_(output)_to_a_specified_location.">seekp():Moves put pointer (output) to a specified location.

tellg():_Gives_the_current_position_of_the_get_pointer.">tellg():Gives the current position of the get pointer.

tellp():_Gives_the_current_position_of_the_put_pointer.">tellp():Gives the current position of the put pointer.

The seekg & tellg functions are associated with get pointer and seekp & tellp functions are associated with put pointer.

What is near far and huge pointers How many bytes are occupied by them?

Near, far, and huge pointers are different types of pointers used to reconcile the different addressing models of the Intel 8086/8088 class processors, running in a 16-bit operating system such as Windows 3.x, as well as any of the newer incarnations running in real mode or virtual 8086 mode.

A near pointer can address something within one 64Kb memory segment, containing only an offset, and it takes two bytes. The segment is implied by context, and is usually the data segment, selected for the addressing model.

A far pointer can address anything in the 1Mb memory1, containing both a segment and an offset, and it takes four bytes.

A huge pointer is a normalised far pointer, which means its offset part is always between 00H and 0FH.

In 32-bit mode a pointer can address anything in 4Gb memory, containing a flat 32-bit offset, and it takes four bytes. (In this mode segments have no significance.) It only works, however, when there is support for it, such as the WIN32 extension of Windows 3.x.

---------------------------------------------------------------------------------------

1In the 80286 or higher, running in protected mode, in OS/2, the segment portion of the pointer is actually a descriptor selector, so 1Mb addressibility depends on the operating system environment.
far huge near pointer is an oxymoron. far points to memory outside of the normal address space. near points to memory within the normal address space, is the default, and usually is not needed. I've never seen huge before. What is the target architecture?
Near, far, and huge pointers are a construct (usually) in the Win16 environment running on an 8086/8088 or later in real mode, such as Visual C/C++ 1.52. In this environment, near pointers are 16 bits, and far and huge pointers are 32 bits.

What is the running time for an insertion at the front of an n- element singly linked list in c plus plus?

Add to the front is constant time O(1). Adding to the end is linear time O(n). If the list maintains a pointer to the last node (as well as the first node), insertions can be done at either end in constant time.

What is the difference between pressing alt plus tab and ctrl plus alt plus tab?

The CTRL key is the only difference. What it actually does depends on the currently active program and/or control, and whether or not the key combo has been implemented or not. If not, the shell processes the key combo. On my system (Windows 7), both combos bring up the task switcher.

Write a program to input N different number and count total odd numbers incurred by the user?

#include

#include

unsigned input_num(std::string prompt)

{

unsigned num = 0;

while (1)

{

std::cout<

std::string input="";

getline (std::cin, input);

std::stringstream ss (input);

if (ss>>num)

break;

std::cout<<"Invalid input.\n";

}

return (num);

}

int main()

{

unsigned nums = input_num ("How many numbers would you like to input? (0 to exit)");

unsigned odds = 0;

while (nums--)

{

unsigned num = input_num ("Please enter a number");

if (num%2)

++odds;

}

std::cout<<"\nYou entered "<

}

Example output

How many numbers would you like to input? (0 to exit): 10

Please enter a number: 0

Please enter a number: 1

Please enter a number: 2

Please enter a number: 3

Please enter a number: 4

Please enter a number: 5

Please enter a number: 6

Please enter a number: 7

Please enter a number: 8

Please enter a number: 9

You entered 5 odd numbers.

Draw a program flowchart to find the least number in a list of 100 numbers?

It's a bit difficult to show a flowchart using nothing but words, but here goes:

start

let list[] be 100 random values

let best be value of list[0]

let index be 1

repeat

is value of list[index] less than best?

YES: let best be value of list[index] {continue}

NO: {continue}

increment index

is index less than 100?

YES: {go to repeat}

NO: {continue}

print value of best

end

Previous answer:

start test number =100 count = count +1 list number =< test number if true testnumber = list number count = 100 goto end else start end

The previous answer assumes 100 to be largest number in the list. What happens when all of the numbers in the list happen to be greater than 100? Also, previous answer exits the loop prematurely as soon as any number equal or smaller than 100 is located. To locate the smallest number in a list, the entire list must be compared with the current best, which is initially taken to be the first number in the list.

What is difference between visual c plus plus and mfc?

That is like comparing apples and trees...

Visual C++ is a development environment that allows one to program in C++, which is a language.

MFC (Microsoft Foundation Classes) is a library to allows one to use C++ to write MS Windows programs using a particular set of API-like calls. It is a library, not a language.

The two cannot really be compared, as they are too different in scope.

How can you access private functions of a class from the Main function in Cpp?

Any member functions and data members declared as 'private' in a class, can only be accessed directly by functions within the class.

They cannot be accessed directly by derived objects, nor from anywhere outside an object of the class, such as from the Main function.

To access private class members, you must rely on what are called accessor functions. Accessor functions are functions inside the class, either public or protected, which automatically have access to private members.

If a function from Main, or elsewhere outside the class hierarchy, needs access, then you need to use publicaccessor functions. For derived class access, you can use protected accessor functions.

Explain Arithmetic micro operation?

The basic arithmetic micro operations are addition, subtraction, increment, decrement, and shift. The arithmetic micro operation defined by the statement:- R3<--R1+R2 specifies an add micro operation. It states that the contents of register R1 are added to the contents of register R2 and the sum transferred to register R3.

The other basic micro operations are :-

symbolic description
designation

R3<- R1+R2 contents of R1 plus R2 transferred to R3 (addition).

R3<- R1+R2 contents of R1 minus R2 transferred to R3 (subtraction).

R2<- R2' complement the contents of R2 (1's complement).

R2<- R2' +1 2's complement of the contents of R2.

R3<- R1 + R2' +1 R1 plus the 2's complement of R2 (subtraction).

R1<- R1+1 Increment the contents of R1 by 1.

R1<- R1 - 1 Decrement the contents of R1 by 1.

The arithmetic micro operations of multiply and divide are not included in the basic arithmetic micro operations. They are implemented by means of a combinational circuit. The multiplication operation is implemented with sequence of add and shift micro operations.

Division operation is implemented with the sequence of subtraction and shift micro operations.

By Vivek Kumar

Which is better - AVL or Red Black Trees?

It depends on what the tree is being used for. If the tree is being used to store data that is not going to be modified very much, than AVL trees are probably better. In most other cases, I'd say Red-Black trees are better.

Why is an array of reference not possible?

Unlike pointer variables and other variables, references have no storage of their own. A reference is simply an alias for an object that already exists in memory (allowing you to refer to the object by its memory address). Since they have no storage of their own it is impossible to create an array of references. You can of course create an array of objects, each of which can then be referenced. You can also have several references to the same object. But you cannot store those references because there is nothing to physically store other than the object itself, which is already stored. For the same reason you cannot reference references nor can you point to references. You can only refer and point to objects (or point to NULL of course).

Write a Program to left shift of an array by one position?

Arrays cannot be left-shifted. That term applies to bit values (it is a bitwise operator). Although conceptually the same, when we shift an array's elements we must traverse the array from the first to penultimate element, copying the next element in place of the current element as we go. This is usually referred to as shunting, and can be done in either direction (left and right).

It's actually much easier think of a left shunt by one element as simply meaning delete the first element. But in reality what you actually do is shunt all the elements (except the first) one position to the left and delete the last element since it will then be a copy of the penultimate element. Alternatively, after shunting all the elements to the left, you can replace the final element with a default value (akin to filling the last bit with a zero as per a bitwise left shift).

The following example demonstrates both techniques using a C++ vector (which is exactly the same as a dynamic array in C but is considerably easier to implement):

#include <iostream>

#include <vector>

// Type definitions to simplify the code.

typedef std::vector<int> int_array;

typedef int_array::iterator it;

void shift_left(int_array& a)

{

// Shift all elements to the left by one position

// and delete the final element.

if( a.size() )

{

unsigned int idx=0;

for(it i=a.begin()+1; i!=a.end(); ++i)

{

a[idx]=a[idx+1];

++idx;

}

a.pop_back();

a.shrink_to_fit();

}

}

void shift_left(int_array& a, int default_value)

{

// Shift all elements to the left by one position

// and replace the final element with the given

// default value.

if( a.size() )

{

unsigned int idx=0;

for(it i=a.begin()+1; i!=a.end(); ++i)

{

a[idx]=a[idx+1];

++idx;

}

a[idx]=default_value;

}

}

void print_array(int_array& a)

{

using namespace std;

for(it i=a.begin(); i!=a.end(); ++i )

cout<<" "<<*i;

cout<<endl;

}

int main()

{

int_array a;

for(int i=0; i<9; ++i )

a.push_back( i+1 );

print_array( a );

shift_left( a );

print_array( a );

shift_left( a, 0 );

print_array( a );

return(0);

}

Output:

1 2 3 4 5 6 7 8 9

2 3 4 5 6 7 8 9

3 4 5 6 7 8 9 0

What is an example of run time polymorphism in c plus plus?

Consult the following program. Three classes are declared, A, B and C, such that B and C both inherit from A. Thus B and C are said to be a "kind of" A. Class A includes a virtual method named action() which is overridden by both B and C. Thus B and C are more specialised than A. All the methods simply print stubs to show which method has been executed.

The main function instantiates one instance of each class and passes all three to the nonpolymorph() function before passing them to the polymorph() function. Both functions accept a reference to an A object and both functions invoke the action() method for that object. Both functions execute the correct method regardless of which type of object is passed.

The nonpolymorphic() function is the least efficient method of enabling runtime polymorphism because the function itself needs to know the exact type of the object being passed in order to invoke the correct method. In this case it examines the last character of the runtime type name and switches accordingly. With more complex class names you might be forced to use nested ifs to compare names, which is even more costly in terms of performance. Once the correct class is determined, a dynamic cast is used for B and C objects to invoke the correct method.

Note that if you should happen to derive new classes from A, you must also update this function to cater for them (adding new cases). In a real program you might have dozens of functions like this and each must be updated accordingly to cater for all new types. This can very quickly become a maintenance nightmare.

The polymorph() function, on the other hand, is not only simpler to implement it requires no additional maintenance whatsoever. It will cater for any class that inherits from A both now and in the future. It is able to achieve runtime polymorphism by virtue of the fact the A class has a virtual function which both B and C override. When you declare a virtual function, you create a virtual table for that class as well as all those that derive from it (that is, one table per class, not one table per object of the class). This consumes a little bit more memory than normal, but the table is simply an array of virtual function pointers that point to the appropriate overrides for that particular class. So the A class table entry will point to A::action(), while the B class table entry will point to B::action(), and so on. Thus you get the expected behaviour without the need for expensive runtime information.

Virtual methods mimic the way objects work in real life to some extent. For instance, imagine the function is you and A, B and C are black box objects that can make a sound at the press of a button on top of the box. Someone places one of these objects in front of you and, although you have no idea what type of object it is, you know you can simply press the button and it will make a sound. In other words you know how the interface works, the object itself decides how that interface is implemented. If the button were not on top of the box then you might have to feel around the box to locate the button. This is akin to using runtime type information to get the additional information you need to use the interface. Sometimes this is required but it is usually a sign of poor design. When interfaces are consistent, then your need to know the type of object is wholly irrelevant.

#include<iostream>

#include<typeinfo>

using namespace std;

struct A

{

virtual void action () { cout << "A::action()\n" << endl; }

};

struct B : A

{

void action () override { cout << "B::action()\n" << endl; }

};

struct C: A

{

void action () override { cout << "C::action()\n" << endl; }

};

void nonpolymorph(A& a)

{

std::string s (typeid(a).name());

switch (s.at( s.size()-1))

{

case ('A'): a.action(); break;

case ('B'): (dynamic_cast<B&>(a)).action(); break;

case ('C'): (dynamic_cast<C&>(a)).action(); break;

}

}

void polymorph(A& a)

{

a.action();

}

int main()

{

A a;

B b;

C c;

nonpolymorph (a);

nonpolymorph (b);

nonpolymorph (c);

polymorph (a);

polymorph (b);

polymorph (c);

}

How do you recursively reverse a singly linked list using c plus plus?

In this case recursion is not necessary, an iterative process is more efficient.

Start by pointing at the head node. While this node has a next node, detach its next node and insert that node at the head. Repeat until the original head node has no next node. At that point the head has become the tail and all the nodes are completely reversed.

The following example shows how this can be implemented, where the list object contains a head node (which may be NULL), and each node has a next node. The tail node's next node is always NULL.

void reverse(list& lst)

{

if( node* p=lst.head )

{

while(p->next)

{

node* n=p.next; // point to the next node

p.next=n.next; // detach the next node

n.next=lst.head; // insert the detached node at the head

lst.head=n; // set the new head node

}

}

}

What is the difference between pre and post processing incrementation?

To increment a value by 1, you have 4 choices:

  • value++;
  • ++value;
  • value += 1;
  • value = value + 1;

Pre and post processing incrementation/decrementation refers to the first two: ++value and value++.

Both do exactly the same, as both will increase the value of 'value' by one.

If we have a situation like this:

int value = 0;

int value1 = 0;

value1 = value++;

This essentially means:

value1 = value;

value = value + 1;

Where ++value means:

value = value + 1;

value1 = value;

What is singleton in c plus plus?

A singleton is a class of object from which only one instance of the object can be instantiated within your program. They are generally used to store global variables or to provide some common functionality, such as an application log. They are generally frowned upon because of their global nature, but when you need common functionality there are far worse ways of going about it than with a singleton.

There are several design patterns for a singleton, but probably the simplest and most common form is shown below. Note the private constructors and assignment operator, and the static member method containing a static variable -- the only instance of the class that can ever exist.

Access to the members (not shown) is via a static call:

CSingleton::Instance().<member>

class CSingleton

{

private:

CSingleton() {}; // Prevent construction outside of the class.

CSingleton(const CSingleton&); // Prevent copy-construction.

CSingleton& operator=(const CSingleton&); // Prevent assignment.

public:

static CSingleton& Instance()

{

static CSingleton singleton;

// Created on first access.

// Destroyed on application exit.

return( singleton );

}

// Specific members omitted. Dependant upon purpose of singleton.

};

How are functions invoked in cpp?

If the function is inline expanded then it is not invoked at all -- there is no function call. However, if the function is not or cannot be inline expanded, a procedure call is invoked. This pushes the calling function's local values onto the stack, followed by the return address, followed by the callee's argument values in reverse order. Control is then passed to the address of the function. The function then pops the arguments off the stack and assigns them to its local parameters (parameters that are passed by value will automatically invoke the copy constructors of those parameters). The function then executes. When a return statement is encountered, the return address is popped from the stack, the return value (if any) is pushed onto the stack, and control is passed to the return address. When a function returns, the return value (if any) and the local values are popped from the stack, and execution continues from where it left off.

Does pure virtual function contain any body?

A pure-virtual method may provide an implementation, but it is not a requirement. If you find that all your derived classes have the exact same implementation (either in whole or in part), then it makes sense to place that implementation within the abstract class, thus ensuring consistency across all derivatives (and thus reducing maintenance). Each derived class can then explicitly call the base class method and optionally augment it with a more specific implementation where required, much as you would with a non-pure virtual method. The only real difference is that you are expected to provide an override for a pure-virtual method, whereas overriding a non-pure virtual method is always optional.

Is vc plus plus object oriented language?

I thought its a development tool..

this is what i got from wiki ---

is a commercial (free version available), integrated development environment (IDE) product from Microsoft for the C, C++, and C++/CLI programming languages. It has tools for developing and debugging C++ code, especially code written for the Microsoft Windows API, the DirectX API, and the Microsoft .NET Framework.

Declare a class called string - it must have constructors which allow definitions of objects in the following form - string name1 string name2minu string name3name2 in cpp?

There's no need to create a class to do this as std::string already does this and a lot more besides. The following class will do exactly as you've asked, but it's really just a wrapper for a std::string and achieves absolutely nothing.

#include<iostream>

class string{

public:

string(std::string s=""):m_str(s){}

string(const string& s):m_str(s.m_str){}

const std::string& get_string(){return(m_str);}

private:

std::string m_str;

};

int main()

{

string name1;

string name2("minu");

string name3(name2);

std::cout << "name1 = '" << name1.get_string().c_str() << "'" << std::endl;

std::cout << "name2 = '" << name2.get_string().c_str() << "'" << std::endl;

std::cout << "name3 = '" << name3.get_string().c_str() << "'" << std::endl;

return(0);

}

Output:

name1 = ''

name2 = 'minu'

name3 = 'minu'

What are the conditions to swap in c plus plus without temporary?

You can swap two integers without temporary storage by bitwise exclusive-or'ing them in a specific sequence...

a ^= b;
b ^= a;
a ^= b;

How can you let the user enter a string and store it into a char array in C plus plus?

Here is an example:

// Example.cpp : Defines the entry point for the console application.

//

#include <stdio.h>

int main();

{

char example; /*Giving example the initialization char*/

printf("What value do you want example to have: ");

scanf("%s", example); /*This is where the value you have entered is being assigned to example*/

printf("Hello %s", example);

return 0;

}

Here is the program running:

What value do you want example to have: dude

Hello dude

Trending Questions
What are input output streams in c plus plus? I want to be a programmer and want to ask does programming requires a lot of math like Geometry-I'm good in math generally but not geometry i can do most of normal math? Is c is the subset of c? Is for loop is faster than while loop in turbo c plus plus compiler? Write a program to swap 2 variables with out using 3rd variable through cout? Write a C program for the following Create a structure employee and accept its data members such as employee name and gender and age and martial status and no of children from the key board and write? What is difference between single and double selection structures? What do you mean by running of a program in c plus plus? What is the need for oops paradigm? What is an ordered list of data structure using c plus plus? Can private members of a class be inherited? Can you write a CPP program to displaying XOR truth table using logical AND OR and NOT? It has been said that C plus plus sits at the center of the modern programming universe Explain this statement? How do you write an algorithm to swap the values of x and y using a temporary variable t? A c comma c plus plus program that can accept first name surname and display it? Why you use constreamh in c plus plus? Show that 8's complement octal and 2's complement binary are exactly equivalent.? What are the advantages and disadvantages of DLL over single linked list? What is the difference between virtual function and function overriding? What is string library functions syntax?